文件操作问题
我定义一个结构体
- C/C++ code
struct Test{ char a[100]; char *b;};在first.cpp中定义一个struct Test obj1;然后赋值,例如strcpy(obj1.a,"12345");obj1.b="123";
然后再将obj1写入到out.txt中。
在second.cpp中同样定义个struct Test obj2,读取out.txt文件,并将读取的结果输出,如何实现?
(1)如果要求将读取的结果同样放入到obj2中,该如何实现?
[解决办法]
- C/C++ code
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;}
[解决办法]
- C/C++ code
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); } }
[解决办法]
- C/C++ code
#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的代码