1.文件写入
追加方式:
void appendwt(){ FILE *pFile = fopen("data.txt","ab+");//使用"ab+"每次都插入到最后面,调用fseek也没用 char *str="hello,world!45%13ad2014/23/13add "; fwrite(str,1,strlen(str),pFile); fflush(pFile); fclose(pFile); }
半中间覆盖:
void randwt(){ FILE *fp; fp=fopen("overwrite.bin","rb+"); //使用rb+模式,可以往半中间插入数据,定义到任何位置 { if(-1 == (fseek(fp,9, SEEK_SET))) /从第9字节开始abcde printf("seek error "); fwrite("abcde",1, 5, fp);
fflush(fp);//flush来刷新流,每次读写后都希望立即看到结果,不用重新打开关闭 fclose(fp); } else { printf("fopen error"); } }
完全覆盖:
void overwt() { FILE *pFile = fopen("data.txt","w+"); fwrite("hello,world!",1,strlen("hello,world!"),pFile); fflush(pFile);
//fseek来移动文件的指针,它指向文件下一个要写入的位置 fseek(pFile,0,SEEK_SET); //文件指针设为起点,写操作覆盖原来的内容 fwrite("欢迎访问",1,strlen("欢迎访问"),pFile); fseek(pFile,0,SEEK_END); //文件指针设为终点 int len = ftell(pFile); //获取文件字节数 char* ch = (char*)malloc(sizeof(char)* (len+1)); //分配内存,多一个字节 memset(ch,0,(len+1)); //清0 // fseek(pFile,0,SEEK_SET); //文件指针指向头部 rewind(pFile); fread(ch,1,len,pFile); //读取文件 fclose(pFile); printf("%s",ch); }
写入结构体:
typedef struct { char c; int h; short n; long m; float f; double d1; char *s; double d2; } st;
void struwt() { FILE *fp; st sa, sb; //定义结构体 char *str = "abcdefg"; //结构体赋值 sa.c = 'K'; sa.h = -3; sa.n = 20; sa.m = 100000000; sa.f = 33.32f; sa.d1 = 78.572; sa.d2 = 33.637; sa.s = str; fp = fopen("st.txt", "w+"); //打开要写的文件 if (!fp) { printf("errror! "); exit(-1); } printf("sa:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f ", sa.c, sa.h, sa.n, sa.m, sa.f, sa.d1, sa.s, sa.d2); printf("sizeof(sa)=%d:&c=%x,&h=%x,&n=%x,&m=%x,&f=%x,&d1=%x,&s=%x,&d2=%x ", sizeof(sa), &sa.c, &sa.h, &sa.n, &sa.m, &sa.f, &sa.d1, &sa.s, &sa.d2); fwrite(&sa, sizeof(sa), 1, fp); //写入结构体 rewind(fp); //重新指向流 fread(&sb, sizeof(sb), 1, fp); //用sb读取 printf("sb:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f ", sb.c, sb.h, sb.n, sb.m, sb.f, sb.d1, sb.s, sb.d2); fclose(fp); //关闭指针 }
2.文件读取
读取结构体:
//从文件读取结构体 void strurd() { FILE *fp; st sb; fp = fopen("st.txt", "r"); //打开文件 if (!fp) { printf("errror! "); exit(-1); } fread(&sb, sizeof(sb), 1, fp); //读取结构体 printf("sb:c=%c,h=%d,n=%d,m=%d,f=%f,d1=%f,s=%s,d2=%f ", sb.c, sb.h, sb.n, sb.m, sb.f, sb.d1, sb.s, sb.d2); printf("sizeof(sb)=%d:&c=%x,&h=%x,&n=%x,&m=%x,&f=%x,&d1=%x,&s=%x,&d2=%x ", sizeof(sb), &sb.c, &sb.h, &sb.n, &sb.m, &sb.f, &sb.d1, &sb.s, &sb.d2); fclose(fp); }
其余方式:
写入一个字符串:
charstr[80]=
"I/Osystem."
;
/*字符串常量存入字符数组*/
int fputs(const char *str, FILE *fp);
scanf后加一个getchar()或者getch()来提示结束输入
继续参考:
http://blog.csdn.net/thefutureisour/article/details/8133931
http://www.cnblogs.com/songQQ/archive/2009/11/25/1610346.html