文件操作问题
我定义一个结构体
struct Test{ char a[100]; char *b;};int readtest(){ Test test; memset(test.buf,0,sizeof(test.buf)); FILE *fp=fopen("test.txt","rb"); if(!fp) return -1; fread(&test,1,sizeof(test),fp); printf("%d",test.num); return 0;}int writetest(){ Test test; memset(test.buf,0,sizeof(test.buf)); test.num=1; memcpy(test.buf,"KKKK",4); FILE *fp; fp=fopen("test.txt","wb"); if(!fp) return -1; fwrite(&test,1,sizeof(test),fp); fclose(fp); return 0;}
[解决办法]
FILE *stream; stream = fopen("fscanf.out", "r"); if(stream == NULL) printf( "The file fscanf.out was not opened\n" ); else { while(feof(stream)) { char s[100] = {0}; fscanf(stream, "%s", s); memcpy(obj2.a,s); memset(s, 0, sizeof(s)); fscanf(stream, "%s", s); memcpy(obj2.b,s); } }
[解决办法]
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct Test{ char a[100]; char *b;}Test;int main(){ Test ds,ss; strcpy(ds.a,"Hello World"); FILE *fp=fopen("temp.txt","w"); fwrite(&ds,1,sizeof(Test),fp); fclose(fp); fp=fopen("temp.txt","r"); fread(&ss,1,sizeof(Test),fp); printf("%s\n",ss.a); fclose(fp); return 0;}//一个C的代码