如何实现结构体和文件之间实现读写--fopen文件流读写(fscanf/fprintf)

来源:互联网 发布:域名未授权 编辑:程序博客网 时间:2024/06/11 18:11

如何实现结构体和文件之间实现读写--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.cduser@10.1.1.5:~/Desktop/testFunction/open$ ./a.out 120 82 50 60 95 100 2


1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 辐射避难所探索废土死了怎么办 大门上边的齿轮滑丝怎么办 国通石油储油卡怎么办 买大棚房受骗了怎么办 朋友做安利天天来我门面怎么办 安利优惠顾客卡怎么办 苹果手机天气温度不显示怎么办? 安利净水器坏了怎么办 安利净水器滤芯盖搭配坏怎么办 安利会员卡过期了怎么办 婴儿吃了润唇膏怎么办? 用错沐浴露洗头怎么办 雅蜜润肤沐浴露怎么办 自煮小火锅水放少了怎么办 安利皇后锅发黑怎么办 宝宝灌肠后不拉屎怎么办 吃蛋白质粉肚子长胖了怎么办 安利产品过期了怎么办 拼多多拼不到人怎么办 被海南大宗骗了怎么办 手机被游戏扣钱怎么办 做酵素剩下的水果怎么办 喝了酵素胃疼怎么办 海科融通不到账怎么办 美团外卖没生意怎么办 淘宝联盟领券销售怎么办 微信返利被骗了怎么办 众筹失败后资金怎么办 健身房不给退卡怎么办 婆婆陷入民间传销组织怎么办 被三生公司骗了怎么办? ppt保存成了图片怎么办 苹果6速度变慢了怎么办 苹果6s速度很慢怎么办 微信支付上限了怎么办 佳享健康骗老人怎么办 宝宝吃了硅胶乳贴怎么办 用完卫生巾后阴部有些不舒服怎么办 指甲上有荧光剂怎么办 小孩吃了荧光剂怎么办 毛巾上有荧光剂怎么办