您的位置:首页 > 其它

C 文件读写

2016-06-01 17:38 351 查看
r 文件只读操作打开一个文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("./test.txt","r");
if(p == NULL)
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
}
return 0;
}
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.4K May 27 16:09 a.out
-rw-rw-r-- 1 chunli chunli  215 May 27 16:09 main.c
-rw-rw-r-- 1 chunli chunli  209 May 27 16:04 test.txt

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!


w 文件只写操作如果文件不存在就创建文件如果文件存在就清空文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("write_file.txt","w");
if(p == NULL)
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
}
return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.4K May 27 16:09 a.out
-rw-rw-r-- 1 chunli chunli  215 May 27 16:09 main.c
-rw-rw-r-- 1 chunli chunli  209 May 27 16:04 test.txt
-rw-rw-r-- 1 chunli chunli    0 May 27 16:09 write_file.txt


从文件读几个字符
chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 479 May 27 16:18 main.c
chunli@ubuntu:~/pointer$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("main.c","r");//打开当前目录下的文件
if(p == NULL)
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c",c);
c = getc(p);
printf("%c  \n",c);
}
return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!


读取文件所有字符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("main.c","r");//打开当前目录下的文件
if(p == NULL)
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p)) != EOF)
{
printf("%c",c);
}
}
return 0;
}

编译运行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("main.c","r");//打开当前目录下的文件
if(p == NULL)
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p)) != EOF)//读取文件所有字符
{
printf("%c",c);
}
}
return 0;
}


文本文件复制
chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 428 May 27 16:32 main.c

main程序
chunli@ubuntu:~/pointer$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p1 = fopen("main.c","r");//打开当前目录下的文件
FILE *p2 = fopen("text.c","w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!

可以看到生成了一个新的文件
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.6K May 27 16:33 a.out
-rw-rw-r-- 1 chunli chunli  428 May 27 16:32 main.c
-rw-rw-r-- 1 chunli chunli  428 May 27 16:33 text.c

查看这个文件
chunli@ubuntu:~/pointer$ cat text.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p1 = fopen("main.c","r");//打开当前目录下的文件
FILE *p2 = fopen("text.c","w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
return 0;
}
chunli@ubuntu:~/pointer$


文件加密
chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 495 May 27 16:40 main.c
主程序
chunli@ubuntu:~/pointer$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void code(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c+=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
int main()
{
code("main.c","code.txt");
}

编译并运行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!

看看产生的文件
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.6K May 27 16:40 a.out
-rw-rw-r-- 1 chunli chunli  495 May 27 16:40 code.txt
-rw-rw-r-- 1 chunli chunli  495 May 27 16:40 main.c

已经完成加密的文件
chunli@ubuntu:~/pointer$ cat code.txt
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*myno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴锁 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m5G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン sx~*wksx23myno2,wksx8m,6,myno8~~,3Echunli@ubuntu:~/pointer$


文件解密
chunli@ubuntu:~/pointer$ ll
total 4.0K
-rw-rw-r-- 1 chunli chunli 923 May 27 16:43 main.c
chunli@ubuntu:~/pointer$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c-=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
void code(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c+=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
int main()
{
code("main.c","code.txt");
decode("code.txt","decode.txt");
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
open sucess!
open sucess!
chunli@ubuntu:~/pointer$ cat decode.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c-=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
void code(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c+=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
int main()
{
code("main.c","code.txt");
decode("code.txt","decode.txt");
}
chunli@ubuntu:~/pointer$


主函数传参数加密解密
主程序 main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c-=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
void code(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c+=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
int main(int argc, char *args[])
{
if(argc < 4)
{
printf("参数1:1加密1:2解密\n");
printf("参数2:1输入文件2:2输出文件\n");
}
else
{
if(atoi(args[1]) == 1)
{
code(args[2],args[3]);
}
if(atoi(args[1]) == 2)
{
decode(args[2],args[3]);

}
}
}
编译
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c
执行
chunli@ubuntu:~/pointer$ ./a.out
参数1:1加密1:2解密
参数2:1输入文件2:2输出文件

执行加密
chunli@ubuntu:~/pointer$ ./a.out 1 main.c  加密了.txt
open sucess!

执行解密
chunli@ubuntu:~/pointer$ ./a.out 2 加密了.txt 解密了.txt
open sucess!

查看加密的文件
chunli@ubuntu:~/pointer$ cat 加密了.txt
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*nomyno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴锁 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m7G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン ysn*myno2myx}~*mrk|*4}|m6myx}~*mrk|*4no}~3*PSVO*4z;*G*pyzox2}|m6*,|,3E99訷濴锁 PSVO*4z<*G*pyzox2no}~6,,3E99蓴耄sp22z;*GG*X_VV3*2z<*GG*X_VV3*3z|sx~p2,yzox*pksv+*fx,3Eov}oz|sx~p2,yzox*mo}}+fx,3Emrk|*m*G*:Ersvo22m*G*qo~m2z;33*+G*OYP3m5G;:E~m2m6z<3Epmvy}o2z;3E99ン pmvy}o2z<3E99ン sx~*wksx2sx~*k|qm6*mrk|*4k|q}eg3sp2k|qm*F*>3z|sx~p2,D;僵蓾<昀砀,3Ez|sx~p2,D;螯耄仄<螯 曱砀,3Eov}osp2k~ys2k|q}e;g3*GG*;3myno2k|q}e<g6k|q}e=g3Esp2k~ys2k|q}e;g3*GG*<3nomyno2k|q}e<g6k|q}e=g3E

查看界面的文件

chunli@ubuntu:~/pointer$ cat 解密了.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c-=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
void code(const char *src,const char *dest)
{
FILE *p1 = fopen(src, "r");//打开当前目录下的文件
FILE *p2 = fopen(dest,"w");//创建文件
if((p1 == NULL) ||(p2 == NULL) )
{
printf("open fail! \n");
}
else
{
printf("open sucess!\n");
char c = 0;
while((c = getc(p1)) != EOF)
{
c+=10;
putc(c,p2);
}
}
fclose(p1);//关闭文件
fclose(p2);//关闭文件
}
int main(int argc, char *args[])
{
if(argc < 4)
{
printf("参数1:1加密1:2解密\n");
printf("参数2:1输入文件2:2输出文件\n");
}
else
{
if(atoi(args[1]) == 1)
{
code(args[2],args[3]);
}
if(atoi(args[1]) == 2)
{
decode(args[2],args[3]);

}
}
}
chunli@ubuntu:~/pointer$


一行一行的读取文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
FILE *p = fopen("main.c","r");
char buf[1024];
while(!feof(p))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p); //从文件读取一行
printf("%s ",buf);

}
fclose(p);
return 0;
}
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
FILE *p = fopen("main.c","r");
char buf[1024];
while(!feof(p))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p); //从文件读取一行
printf("%s ",buf);

}
fclose(p);
return 0;
}
}
chunli@ubuntu:~/pointer$


文件复制 一行一行的复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
FILE *p1 = fopen("main.c","r");
FILE *p2 = fopen("cpoy.txt","w");
char buf[1024];
while(!feof(p1))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p1);//从文件中读取
fputs(buf,p2);//写入到另一个文件
}
fclose(p1);
fclose(p2);
return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
chunli@ubuntu:~/pointer$ ll
total 20K
-rwxrwxr-x 1 chunli chunli 8.7K May 27 18:51 a.out
-rw-rw-r-- 1 chunli chunli  325 May 27 18:51 cpoy.txt
-rw-rw-r-- 1 chunli chunli  323 May 27 18:51 main.c
chunli@ubuntu:~/pointer$ cat cpoy.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
FILE *p1 = fopen("main.c","r");
FILE *p2 = fopen("cpoy.txt","w");
char buf[1024];
while(!feof(p1))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p1);//从文件中读取
fputs(buf,p2);//写入到另一个文件
}
fclose(p1);
fclose(p2);
return 0;
}


利用一行一行的读取加密文件
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(char *s)
{
int len = strlen(s);
while(len--)
*s++ -= 10;
}

void code(char *s)
{
int len = strlen(s);
while(len--)
*s++ += 10;
}

int main(int argc, char *args[])
{
FILE *p1 = fopen("main.c","r");
FILE *p2 = fopen("cpoy1.txt","w");
FILE *p3 = fopen("cpoy2.txt","w");
char buf[1024];
while(!feof(p1))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p1);	//从文件中读取
code(buf);			//加密这个字符串
fputs(buf,p2);			//写入到另一个文件

decode(buf);			//解密字符串
fputs(buf,p3);			//写入到另一个文件

}
fclose(p1);//关闭文件
fclose(p2);
fclose(p3);
return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
chunli@ubuntu:~/pointer$ cat cpoy1.txt
-sxmno*F}~nsy8rH-sxmno*F}~nvsl8rH-sxmno*F}~|sxq8rHysn*nomyno2mrk|*4}3sx~*vox*G*}~|vox2}3Ersvo2vox7734}55*7G*;:Eysn*myno2mrk|*4}3sx~*vox*G*}~|vox2}3Ersvo2vox7734}55*5G*;:Esx~*wksx2sx~*k|qm6*mrk|*4k|q}eg3PSVO*4z;*G*pyzox2,wksx8m,6,|,3EPSVO*4z<*G*pyzox2,mzy;8~~,6,,3EPSVO*4z=*G*pyzox2,mzy<8~~,6,,3Emrk|*pe;:<>gErsvo2+poyp2z;3399ヴ需耄垰§pqo~}2p6}soyp2p36z;3E99耄 myno2p3E99僵餮滽p~}2p6z<3E99烴諶耄nomyno2p3E99滽p~}2p6z=3E99烴諶耄pmvy}o2z;3E99ン pmvy}o2z<3Epmvy}o2z=3E|o|x*:Echunli@ubuntu:~/pointer$

chunli@ubuntu:~/pointer$ cat cpoy2.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decode(char *s)
{
int len = strlen(s);
while(len--)
*s++ -= 10;
}

void code(char *s)
{
int len = strlen(s);
while(len--)
*s++ += 10;
}

int main(int argc, char *args[])
{
FILE *p1 = fopen("main.c","r");
FILE *p2 = fopen("cpoy1.txt","w");
FILE *p3 = fopen("cpoy2.txt","w");
char buf[1024];
while(!feof(p1))//判断是不是到了文件结束
{
fgets(buf,sizeof(buf),p1);	//从文件中读取
code(buf);			//加密这个字符串
fputs(buf,p2);			//写入到另一个文件

decode(buf);			//解密字符串
fputs(buf,p3);			//写入到另一个文件

}
fclose(p1);//关闭文件
fclose(p2);
fclose(p3);
return 0;
}


从文件格式化读取
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
char buf[1024];
sprintf(buf,"%s--%d","1234",5678);//格式化输出到 -> 字符串数组
printf("%s\n",buf);

FILE *p = fopen("hello.txt","w");
fprintf(p,"%s %d \n",buf,9999);//格式化输出到文件
fclose(p);

FILE *p1 = fopen("hello.txt","r");
fscanf(p1,"%s\n",buf);//从文件格式化输入 遇到空格就会停止
printf("%s \n",buf);

FILE *p2 = fopen("hello.txt","r");
fgets(buf,99,p2);//从文件格式化输入 遇到空格不会停止
printf("%s",buf);
fclose(p);

return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
1234--5678
1234--5678
1234--5678 9999

chunli@ubuntu:~/pointer$ cat hello.txt
1234--5678 9999


文件输入初步1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
char buf[1024];
FILE *p = fopen("hello.txt","w");
for(int a = 0;a<10;a++)
{
sprintf(buf,"%s--%d","1234",a);//格式化输出到 -> 字符串数组
fprintf(p,"%s %d \n",buf,a*a);//格式化输出到文件
}
fclose(p);

return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
chunli@ubuntu:~/pointer$ cat hello.txt
1234--0 0
1234--1 1
1234--2 4
1234--3 9
1234--4 16
1234--5 25
1234--6 36
1234--7 49
1234--8 64
1234--9 81


获取键盘输入到文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
char buf[1024];
FILE *p = fopen("hello.txt","w");
for(int a = 0;a<3;a++)
{
gets(buf);
fprintf(p,"%s\n",buf);//格式化输出到文件
}
fclose(p);

return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
main.c: In function ‘main’:
main.c:10:3: warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(buf);
^
/tmp/ccESW6f6.o: In function `main':
main.c:(.text+0x54): warning: the `gets' function is dangerous and should not be used.
123
1qaz
asdfghj
chunli@ubuntu:~/pointer$ cat hello.txt
123
1qaz
asdfghj


追加写入文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
char buf[1024];
FILE *p = fopen("hello.txt","a"); //对已有文件追加内容如果文件不存在就创建
for(int a = 0;a<3;a++)
{
gets(buf);
fprintf(p,"%s\n",buf);//格式化输出到文件
}
fclose(p);

return 0;
}

chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out
main.c: In function ‘main’:
main.c:10:3: warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(buf);
^
/tmp/cc1C6VG0.o: In function `main':
main.c:(.text+0x54): warning: the `gets' function is dangerous and should not be used.
qwertfg
12345
1qaz
chunli@ubuntu:~/pointer$ cat hello.txt
123
1qaz
asdfghj
qwertfg
12345
1qaz


linux 系统之间通过网络传输文本文件1一次发送一个字符
参考我的linux网络通信
http://990487026.blog.51cto.com/10133282/1773543
替换主函数就可以了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
int main(int argc, char *args[])
{
if (argc < 3)
{
printf("请输入2个参数 1发送/2接收需要发送文件名/接收另存为文件名 \n");
return 0;
}

if (atoi(args[1]) == 1)
{
char destined[] = "10.11.12.4";
FILE *read = fopen(args[2],"r");
char c = 0;
while((c = fgetc(read)) != EOF)
{
send_socket(destined, 8080, &c, sizeof(char));
//printf("%c",c);
}
c = EOF;
send_socket(destined, 8080, &c, sizeof(char));
}

if (atoi(args[1]) == 2)
{
FILE *write = fopen(args[2],"w");
bind_socket(8080);
char buf[100] = {0};
char IP[100] = { 0 };
while(1)
{

recv_socket(buf, 1, IP);
if(buf[0] == EOF) break;
fprintf(write, "%s", buf);
}
}

return 0;
}
编译
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

发送端执行
chunli@ubuntu:~/pointer$ ./a.out 1 main.c

接收端执行
chunli@ubuntu:~/pointer$ ./a.out 2 recieve


linux 系统之间通过网络传输文本文件2一次发送一行字符
参考我的linux网络通信
http://990487026.blog.51cto.com/10133282/1773543
替换主函数就可以了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
int main(int argc, char *args[])
{
if (argc < 3)
{
printf("请输入2个参数 1发送/2接收需要发送文件名/接收另存为文件名 \n");
return 0;
}

if (atoi(args[1]) == 1)
{
char destined[] = "10.11.12.4";
FILE *read = fopen(args[2],"r");
char buf[999] = {0};
while(!feof(read))
{
fgets(buf, sizeof(buf), read);//从p1读取一行
send_socket(destined, 8080, buf, strlen(buf));
}
buf[0] = EOF;
send_socket(destined, 8080, buf, sizeof(char));
}

if (atoi(args[1]) == 2)
{
FILE *write = fopen(args[2],"w");
bind_socket(8080);
char buf[999] = {0};
char IP[100] = {0};
while(1)
{
memset(buf, 0, sizeof(buf));
recv_socket(buf, sizeof(buf), IP);
fprintf(write, "%s", buf);
if(buf[0] == EOF)
{
break;
}
}
}

return 0;
}

编译
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

接收端运行
chunli@ubuntu:~/pointer$ ./a.out 2 recieve.c

发送端运行
chunli@ubuntu:~/pointer$ cat send
tcpdump详细用法

第一种是关于类型的关键字主要包括hostnetport, 例如 host 210.27.48.2指明 210.27.48.2是一台主机net 202.0.0.0 指明 202.0.0.0是一个网络地址port 23 指明端口号是23。如果没有指定类型缺省的类型是host.

第二种是确定传输方向的关键字主要包括src , dst ,dst or src, dst and src ,这些关键字指明了传输的方向。举例说明src 210.27.48.2 ,指明ip包中源地址是210.27.48.2 , dst net 202.0.0.0 指明目的网络地址是202.0.0.0 。如果没有指明方向关键字则缺省是src or dst关键字。

chunli@ubuntu:~/pointer$ ./a.out 1 send

接收端查看
chunli@ubuntu:~/pointer$ cat recieve
tcpdump详细用法

第一种是关于类型的关键字主要包括hostnetport, 例如 host 210.27.48.2指明 210.27.48.2是一台主机net 202.0.0.0 指明 202.0.0.0是一个网络地址port 23 指明端口号是23。如果没有指定类型缺省的类型是host.

第二种是确定传输方向的关键字主要包括src , dst ,dst or src, dst and src ,这些关键字指明了传输的方向。举例说明src 210.27.48.2 ,指明ip包中源地址是210.27.48.2 , dst net 202.0.0.0 指明目的网络地址是202.0.0.0 。如果没有指明方向关键字则缺省是src or dst关键字。


更高效率。文件发送
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myudp.h"
#include <sys/stat.h>
int main(int argc, char *args[])
{
if (argc < 3)
{
printf("请输入2个参数 1发送/2接收需要发送文件名/接收另存为文件名 \n");
return 0;
}

if (atoi(args[1]) == 1)
{
char destined[] = "10.11.12.4";
FILE *read = fopen(args[2],"r");
struct stat st;
stat(args[2], &st);			//调用stat函数会把文件的相关信息放入结构st当中
char *buf = (char *)malloc(st.st_size);	//在堆里面根据文件实际大小动态分配一个数组
char *log = buf;
memset(buf, 0, st.st_size);		//把堆当中申请的内存清空
while(!feof(read))
{
char tmp[100] = {0};
fgets(tmp, sizeof(tmp), read);//从p1读取一行
strcat(buf, tmp);
}
send_socket(destined, 8080, buf, strlen(buf));
char c = EOF;
send_socket(destined, 8080, &c, sizeof(char));
//free(log);
//fclose(read);
}

if (atoi(args[1]) == 2)
{
FILE *write = fopen(args[2],"w");
bind_socket(8080);
char buf[999] = {0};
char IP[100] = {0};
while(1)
{
memset(buf, 0, sizeof(buf));
recv_socket(buf, sizeof(buf), IP);
fprintf(write, "%s", buf);
if(buf[0] == EOF)
{
break;
}
}
}

return 0;
}

编译
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c -L. -lmyudp

chunli@ubuntu:~/pointer$ cat send
tcpdump详细用法

第二种是确定传输方向的关键字主要包括src , dst ,dst or src, dst and src

发送端
chunli@ubuntu:~/pointer$ ./a.out 1 send

接收端
chunli@ubuntu:~/pointer$ ./a.out 2 recieve


【产生一定数量的随机数保存到文件再从文件中读出并排序保存到另外一个文件中】
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int create_rand(int num)
{
srand((unsigned int)time(NULL));
FILE *p = fopen("a.txt","w");
if(p == NULL) return 0;
for(int i = 0; i< num;i++)
{
fprintf(p,"%d \n",rand());
}
fclose(p);
return 0;
}

int  read_arr(int *arr,int len)
{
FILE *p = fopen("a.txt","r");
if(p == NULL) return 0;
int i = 0;
int value = 0;
while (!feof(p) && len --)
{
fscanf(p,"%d",&value);
arr[i] =  value;
i++;
}
fclose(p);
return 0;
}

int  write_arr(int *arr,int len)
{
FILE *p = fopen("b.txt","w");
if(p == NULL) return 0;
for(int i = 0;i<len;i++)
{
fprintf(p,"%d\n",arr[i]);
}
fclose(p);
return 0;
}

void printf_arr(int *arr,int len)
{
for(int i = 0;i<len;i++)
{
printf("arr[%d] = %d \n" ,i,arr[i]);
}
}

void bobble(int *arr,int len)
{
for(int i = 0;i<len;i++)
{
for(int j = 1;j<len-i;j++)
{
if(arr[j] < arr[j-1])
{
int tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
}
}

int main()
{
int arr[9999] = {0};
create_rand(sizeof(arr)/sizeof(int));
read_arr(arr,sizeof(arr)/sizeof(int));
printf_arr(arr,sizeof(arr)/sizeof(int));
bobble(arr,sizeof(arr)/sizeof(int));
printf("-------------------------------------\n");
printf_arr(arr,sizeof(arr)/sizeof(int));
write_arr(arr,sizeof(arr)/sizeof(int));
}

编译并执行
chunli@ubuntu:~/pointer$ gcc -std=c99 main.c && ./a.out


fseek函数
ftell函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
char buf[999]={0};
int num = 0;
FILE *p = fopen("text","r");
if(p == NULL) return 0;

/*	文件位置设定	*/
fseek(p,0,SEEK_SET);	//SEEK_SET,设定文件开始位置
//fseek(p,-6,SEEK_END);//SET_END,从文件末尾向前偏移N个字节为有效(负数向前移动正数向后移动)
printf("当前位置%ld \n",ftell(p));

while(!feof(p))
{
memset(buf,0,sizeof(buf));
//fseek(p,3,SEEK_CUR);//在当前位置向后偏移N个字节
fgets(buf,sizeof(buf),p);
printf("当前位置%ld\t%s",ftell(p),buf);
}
}

编译运行
chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
当前位置0
当前位置8	abcdefg
当前位置21	Hello World!
当前位置45	Welcome to chunli home!
当前位置68	欢迎学习C语言
当前位置75	123456
当前位置103	此行下面有一个空行
当前位置104
当前位置104	chunli@ubuntu:~/file$


fprintf()是临时写到内存中的
fflush函数

将数据实时写入磁盘
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
char buf[20]={0};
int num = 0;
FILE *p = fopen("text","w");
if(p == NULL) return 0;
while(1)
{
memset(buf,0,sizeof(buf));
scanf("%s",buf);
if(strncmp(buf,"exit",4) == 0) {break;} //当输入的字符是exit就退出
fprintf(p,"%s \n",buf);                 //将数据写入临时内存
fflush(p);                              //将本次的数据从内存同步到磁盘(效率极低)
}
fclose(p);//此时才将数据从内存写入到磁盘
return 0;
}
chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
12342141

exit


fwrite写二进制文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *p = fopen("text.dat","wb");
if(p == NULL) return 0;
char buf[100] = {"1111\r\n1111\r\n2222\r\n3333"};
//fwrite(buf,1,strlen(buf),p);//这两种方式是一样的
fwrite(buf,strlen(buf),1,p);//一次写strlen的长度写1次
fclose(p);
return 0;
}

文件二进制加密解密
chunli@ubuntu:~/file$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CODE 0x1234
int main()
{
//文件加密哈
{
FILE *p1 = fopen("main.c","rb");
if(p1 == NULL) return 0;

FILE *p2 = fopen("1加密.dat","wb");
if(p2 == NULL) return 0;

while(!feof(p1))
{
char buf[999] = {0};
fgets(buf,sizeof(buf),p1);// 读一行字符串
size_t len = strlen(buf);
for(int i = 0;i<len;i++)//处理每个字符串
{
int tmp = buf[i] ^ CODE ;//加密并转换为int
fwrite(&tmp,sizeof(int),1,p2);//写入文件
}
}
fclose(p1);
fclose(p2);
}
//文件解密
{
FILE *p1 = fopen("1加密.dat","rb");
if(p1 == NULL) return 0;

int tmp = 0 ;
FILE *p2 = fopen("2解密.dat","wb");
if(p2 == NULL) return 0;

while(fread(&tmp,sizeof(int),1,p1)) //此处不能用feof判断
{
char c = tmp ^ CODE;         //将读取的int解密转换为char
fwrite(&c,sizeof(char),1,p2);
}
fclose(p1);
fclose(p2);
}

return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99 main.c && ./a.out
chunli@ubuntu:~/file$ ll
total 24K
-rw-rw-r-- 1 chunli chunli 3.9K May 31 16:27 1加密.dat
-rw-rw-r-- 1 chunli chunli  973 May 31 16:27 2解密.dat
-rwxrwxr-x 1 chunli chunli 8.8K May 31 16:27 a.out
-rw-rw-r-- 1 chunli chunli  973 May 31 16:28 main.c


二进制文件复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
int main(int argc,char *args[])
{
if(argc < 3)
{
printf("参数不够 \n");
return 0;
}

FILE *p1 = fopen(args[1],"rb");
if(p1 == NULL)
{
printf("打开文件%s失败\n",args[1]);
return 0;
}

FILE *p2 = fopen(args[2],"wb");
if(p2 == NULL)
{
printf("打开文件%s失败\n",args[2]);
return 0;
}
/*		方式一		*/
char buf[10] = {0};			//设定缓存区大小
while(!feof(p1)) //此处不能用feof判断
{
size_t size = fread(buf,1,sizeof(buf),p1);
//printf("%ld \n",size);		//查看本次读取了多少个有效字节
fwrite(buf,1,size,p2);		//写入有效个字节
}
/*		方式二  最高效
struct stat st;
stat(args[1],&st);
char *buf = malloc(st.st_size);
fread(buf,st.st_size,1,p1);
fwrite(buf,st.st_size,1,p2);
free(buf);
*/

fclose(p1);
fclose(p2);

return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99 -o mycp main.c && ./mycp /sbin/ifconfig  ./ifconfig_copy
chunli@ubuntu:~/file$ chmod +x ifconfig_copy
chunli@ubuntu:~/file$ ./ifconfig_copy
eth0      Link encap:Ethernet  HWaddr 00:0c:29:ed:22:c1
inet addr:10.11.12.4  Bcast:10.11.12.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:feed:22c1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:85812 errors:0 dropped:14 overruns:0 frame:0
TX packets:55751 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:15630825 (15.6 MB)  TX bytes:26146882 (26.1 MB)


结构体与文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int ID;
char name[100];
};
int main()
{
//		把结构体写入文件
{
struct student st[] ={
{0,"刘德华0"},
{1,"刘德华1"},
{2,"刘德华2"},
{3,"刘德华3"},
{4,"刘德华4"},
{5,"刘德华5"},
{6,"刘德华6"},
{7,"刘德华7"},
{8,"刘德华8"},
{9,"刘德华9"},
};
FILE *p = fopen("data","wb");
if(p == NULL)
{
printf("创建data文件失败\n");
return 0;
}
fwrite(st,sizeof(struct student),10,p);
fclose(p);
}
//		修改结构体文件
{
struct student st = {45,"周杰伦"};
FILE *p = fopen("data","rb+");
if(p == NULL)
{
printf("打开文件data失败\n");
return 0;
}
fseek(p,sizeof(st)*2,SEEK_SET);//将第3个位置的信息修改为st
fwrite(&st,sizeof(st),1,p);
fclose(p);
}
//		从文件中读出结构体
{
FILE *p = fopen("data","rb");
if(p == NULL)
{
printf("打开文件data失败\n");
return 0;
}
struct student st;
memset(&st,0,sizeof(st));
while(fread(&st,sizeof(st),1,p))
{
printf("Id=%u,name=%s\n",st.ID,st.name);
}
fclose(p);

}

return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
Id=0,name=刘德华0
Id=1,name=刘德华1
Id=45,name=周杰伦
Id=3,name=刘德华3
Id=4,name=刘德华4
Id=5,name=刘德华5
Id=6,name=刘德华6
Id=7,name=刘德华7
Id=8,name=刘德华8
Id=9,name=刘德华9


从结构体文件中读出指定的数据并返回耗时
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct student
{
int ID;
char name[100];
};

int main()
{
//		把结构体写入文件
{
struct student st[] ={
{0,"刘德华0"},
{1,"刘德华1"},
{2,"刘德华2"},
{3,"刘德华3"},
{4,"刘德华4"},
{5,"刘德华5"},
{6,"刘德华6"},
{7,"刘德华7"},
{8,"刘德华8"},
{9,"刘德华9"},
};
FILE *p = fopen("data","wb");
if(p == NULL)
{
printf("创建data文件失败\n");
return 0;
}
fwrite(st,sizeof(struct student),10,p);
fclose(p);
}
//		从文件中读出结构体
{
FILE *p = fopen("data","rb");
if(p == NULL)
{
printf("打开文件data失败\n");
return 0;
}
struct student st;
unsigned int ID = 0;
clock_t ct ;
while(1)
{
memset(&st,0,sizeof(st));
printf("请输入ID: ");
scanf("%u",&ID);
if(ID == 0) {break;}
ct = clock();
fseek(p,sizeof(st)*(ID-1),SEEK_SET);
fread(&st,sizeof(st),1,p);
ct = clock() - ct;
printf("ms = %ld,Id=%u,name=%s\n",ct,st.ID,st.name);
}
fclose(p);

}

return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
请输入ID: 1
ms = 40,Id=0,name=刘德华0
请输入ID: 1
ms = 9,Id=0,name=刘德华0
请输入ID: 9
ms = 9,Id=8,name=刘德华8
请输入ID: 4
ms = 9,Id=3,name=刘德华3


结构体数组信息保存到二进制文件从二进制文件读出在结构体数组中插入一条记录保存到文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct student
{
int ID;
char name[100];
};

void insert(struct student *p,int len)
{
for(int i = len-1;i>=2;i--)
{
p[i+1] = p[i];
}
}

int main()
{
//		把结构体写入文件
{
struct student st[] ={
{0,"刘德华"},
{1,"宏碁"},
{2,"戴尔"},
{3,"华为"},
{4,"阿里巴巴"},
{5,"51CTO"},
{6,"清华大学"},
{7,"贝尔实验室"},
{8,"阿基米德"},
{9,"C/C++"},
{11,"六一儿童节"},
};
FILE *p = fopen("data","wb");
if(p == NULL)
{
printf("创建data文件失败\n");
return 0;
}
fwrite(st,sizeof(struct student),sizeof(st)/sizeof(struct student),p);
fclose(p);
}
//		从文件中读出结构体
{
FILE *p = fopen("data","rb");
if(p == NULL)
{
printf("打开文件data失败\n");
return 0;
}
struct student *pst = calloc(100,sizeof(struct student)); //在内存的动态存储区中分配n个长度为size的连续空间函数返回一个指向分配起始地址的指针
int index = 0;
while(fread(&pst[index],sizeof(struct student),1,p))//一直读
{
printf("读文件%d-> Id=%u,name=%s\n",index,pst[index].ID,pst[index].name);
index++;
}
fclose(p);

//		在这个结构体中插入数据
insert(pst,index);//此时从序号为2的结构体index都向后移动了以为
pst[2].ID = 12;		//为新的结构体赋值
strcpy(pst[2].name,"Windows 怎么样");

//		遍历这个结构体
for(int i = 0;i < index + 1;i++)
{
printf("遍历结构体%d -> ID = %u,name=%s \n",i,pst[i].ID,pst[i].name);
}
//将修改的结果保存到文件
{
FILE *p = fopen("data","wb");
if(p == NULL)
{
printf("创建文件失败\n");
return 0;
}
fwrite(&pst,sizeof(struct student),index+1,p);
fclose(p);
}

}

return 0;
}

chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
读文件0-> Id=0,name=刘德华
读文件1-> Id=1,name=宏碁
读文件2-> Id=2,name=戴尔
读文件3-> Id=3,name=华为
读文件4-> Id=4,name=阿里巴巴
读文件5-> Id=5,name=51CTO
读文件6-> Id=6,name=清华大学
读文件7-> Id=7,name=贝尔实验室
读文件8-> Id=8,name=阿基米德
读文件9-> Id=9,name=C/C++
读文件10-> Id=11,name=六一儿童节
遍历结构体0 -> ID = 0,name=刘德华
遍历结构体1 -> ID = 1,name=宏碁
遍历结构体2 -> ID = 12,name=Windows 怎么样
遍历结构体3 -> ID = 2,name=戴尔
遍历结构体4 -> ID = 3,name=华为
遍历结构体5 -> ID = 4,name=阿里巴巴
遍历结构体6 -> ID = 5,name=51CTO
遍历结构体7 -> ID = 6,name=清华大学
遍历结构体8 -> ID = 7,name=贝尔实验室
遍历结构体9 -> ID = 8,name=阿基米德
遍历结构体10 -> ID = 9,name=C/C++
遍历结构体11 -> ID = 11,name=六一儿童节


我有一份学生名单文件需要为每个学生随机ID值存储到文件再读出来按照ID顺序打印到屏幕
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct student
{
unsigned int ID;
char name[20];
};

void create_num(int arr[],int len)//将传过来的数组装入乱序随机值
{
int i = 0;
int j = 0;
srand((unsigned int)time(NULL));
while(i<len)
{
int tmp = rand() % len;
for(j = 0;j<i;j++)
{
if(arr[j] == tmp)
{
break;
}
}
if(j == i)
{
arr[i] = tmp;
i++;
}
}
}

int main()
{
////////	从文件中读取信息修改存储到文件		///////////////////////////////////////////////
{
srand((unsigned int)time(NULL));
FILE *p  = fopen("student","r");
if(p == NULL ) {return 0;}
FILE *p2 = fopen("data","wb");
if(p2 == NULL ) {return 0;}
struct student st = {0,""};
char buf[100] = {0};
int arr[100];				//定义一个数组
create_num(arr,sizeof(arr)/sizeof(int));//为数组载入n个乱序不重复个数值
int index = 0;
while(!feof(p))
{
fgets(st.name,sizeof(st.name),p);
int len = strlen(st.name);
if(st.name[len-1] == '\n'){st.name[len-1] = 0;}//去除每一行的'\n'字符
st.ID = arr[index++];		//把数组的乱序不重复值拿出来
//printf("%d,%s \n",st.ID,st.name);
fwrite(&st,sizeof(st),1,p2);
}
fclose(p);
fclose(p2);
}
////////	从文件中读取	////////////////////////////////////////////////
{
FILE *p = fopen("data","rb");
if(p == NULL) {return 0;}
struct student st[100];
struct student tmp;
int index = 0;
while( fread(&st[index++],sizeof(struct student),1,p));//将文件读取到内存
/////////	将结构体按照ID排序一下 		//////////////////////////////////////////////////
for(int i=1;i<index-1;i++)
{
for(int j =1;j<index-i-1;j++)
{
if(st[j].ID < st[j-1].ID)
{
tmp    = st[j];
st[j]  = st[j-1];
st[j-1]= tmp;
}
}
}
////////////	遍历输出结构体信息	//////////////////////////////////////////
for(int i = 0;i<index -2;i++)
{
printf("%d,%s \n",st[i].ID,st[i].name);
}
}
return  0;
}
学生姓名为文件
chunli@ubuntu:~/file$ cat student
张三丰
李小龙
朴槿惠
联想
戴尔
孙悟空
收音机
银河系
西瓜

编译执行
chunli@ubuntu:~/file$ gcc -std=c99  main.c && ./a.out
16,戴尔
23,联想
41,孙悟空
55,西瓜
58,收音机
71,银河系
74,张三丰
84,李小龙
97,朴槿惠
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  文件 C 读写