二进制文件写入与读入
程序要求:有五个学生,每个学生有三门课的成绩,从键盘上输入学生的学号,姓名,三门课成绩,把它们存放到磁盘文件bat中,并从该文件中能读出显示。
#include<stdio.h>
#include<stdlib.h>
#define stu struct student
stu
{
char num[5];
char name[20];
float sc1;
float sc2;
float sc3;
}s[5];
void save()
{
FILE *fp;
int i;
if((fp=fopen("student.dat","wb"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<5;i++)
{
if(fwrite(&s[i],sizeof(stu),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
void load()
{
FILE *fp;
int i;
if((fp=fopen("student.dat","rb"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<5;i++)
{
if(fread(&s[i],sizeof(stu),1,fp)!=1)
printf("file read error\n");
printf("%s %s %.1f %.1f %.1f\n",s[i].num,s[i].name,s[i].sc1,s[i].sc2,s[i].sc3);
}
fclose(fp);
}
void main()
{
int i;
for(i=0;i<5;i++)
scanf("%s%s%f%f%f",s[i].num,s[i].name,&s[i].sc1,&s[i].sc2,&s[i].sc3);
save();
load();
}
运行结果
01 MissFortune 98 95 82
02 Henry 95 87 95
03 ZhangJingyue 82 73 92
04 Yuyan 82 90 78
05 Test 100 100 100
01 MissFortune 98.0 95.0 82.0
02 Henry 95.0 87.0 95.0
03 ZhangJingyue 82.0 73.0 92.0
04 Yuyan 82.0 90.0 78.0
05 Test 100.0 100.0 100.0