结构体数据怎么放到文件里?从文件中又怎么读出结构体数据?
比如下面程序: 建立结构体数组school[10],怎么存到文件里,又怎么读出?
#include"stdio.h"
#include"stdlib.h"
main()
{ int i;
FILE*fp;
struct school //定义结构体
{ int num;
int item;
int order;
int score;
}
school[10];
//写入文件
if((fp=fopen("d:\\test\\gxp.txt","w"))==NULL)
{ printf("can not open file");
exit(0);
}
for(i=0;i<2;i++)
{ printf("请输入学校编号\n");
scanf("%d",&school[i].num);
printf("请输入项目编号\n");
scanf("%d",&school[i].item);
printf("请输入名次\n");
scanf("%d",&school[i].order);
printf("请输入分数\n");
scanf("%d",&school[i].score);
fprintf(fp,"%d%d%d%d",&school[i].num,&school[i].item,&school[i].order,&school[i].score);
};
fclose(fp);// 关闭文件
//读文件
if((fp=fopen("d:\\test\\gxp.txt","r"))==NULL)
{ printf("can not open file");
exit(0);
}
for(i=0;i<2;i++)
fscanf(fp,"%d%d%d%d\n",&school[i].num,&school[i].item,&school[i].order,&school[i].score);
for(i=0;i<2;i++)
printf("%d %d %d %d\n",school[i].num,school[i].item,school[i].order,school[i].score);
fclose(fp);// 关闭文件
}