如何实现结构体和文件之间实现读写--fopen文件流读写(fscanf/fprintf)
目的:
#1. 把结构体数据写入文件;
#2. 把文件中数据到处到结构体;
用到的函数:
FILE *fopen(const char *path, const char *mode);
int fscanf(FILE *stream, const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
以下是测试函数:
<pre name="code" class="cpp">#include <stdio.h>
#include <string.h>
FILE *stream;
typedef struct test
{
int a;
int b;
int c;
int d;
int e;
int f;
int g;
}STest;
FILE *openHistoryFile(const char *path, const char *mode)
{
return fopen(path, mode);
}
int writeHistoryFile(FILE *stream, STest test)
{
return fprintf(stream,"%d %d %d %d %d %d %d\n", test.a,test.b,test.c,test.d,test.e,test.f,test.g);
}
int readHistoryFile(FILE *stream, STest *test)
{
return fscanf(stream, "%d %d %d %d %d %d %d", &test->a,&test->b,&test->c,&test->d,&test->e,&test->f,&test->g);
}
int main(void)
{
STest test = {120, 82, 50, 60, 95, 100, 2};
STest readTest = {0};
stream = openHistoryFile("test.txt", "ab+");
//memset(&test, 0 , sizeof(STest));
if(stream==NULL)
{
printf("The file test.txt opened\n");
}
else
{
writeHistoryFile(stream, test);
fseek(stream,0L,SEEK_SET);
memset(&readTest, 0 , sizeof(STest));
while(readHistoryFile(stream, &readTest) != EOF)
{
/*print the data value*/
printf("%d %d %d %d %d %d %d\n",readTest.a,readTest.b,readTest.c,readTest.d,readTest.e,readTest.f,readTest.g);
}
fclose(stream);
}
return 0;
}
以下是测试结果:
duser@10.1.1.5:~/Desktop/testFunction/open$ gcc fopenRW.c
duser@10.1.1.5:~/Desktop/testFunction/open$ ./a.out
120 82 50 60 95 100 2