#include<stdio.h>
main()
{
FILE *fp;
int i;
struct stu //定义结构体类型
{
char name[15];
char num[6];
float score[2];
}student; //说明结构体变量
if((fp=fopen("test.txt","w"))==NULL) //以文本只写方式打开文件
{
printf("can't open file,strike any key exit!");
exit(0);
}
printf("input data:\n");
for(i=0;i<2;i++)
{
scanf("%s%s%f%f",student.name,student.num,&student.score[0],&student.score[1]); //从键盘上输入
fprintf(fp,"%s%s%7.2f%7.2f",student.name,student.num,student.score[0],student.score[1]);
} //写入文件
fclose(fp); //关闭文件
if((fp=fopen("test.txt","r"))==NULL) //以文本只读方式重新打开文件
{
printf("cannot open file");
exit(0);
}
printf("output from file:\n");
while(fscanf(fp,"%s%s%f%f\n",student.name,student.num,&student.score[0],&student.score[1])!=EOF);//从文件读入
printf("%s %s %7.2f %7.2f\n",student.name,student.num,student.score[0],student.score[1]); //显示到屏幕
fclose(fp); //关闭文件
}
}