代码
#include<stdio.h>
#include<stdlib.h>
#define N 5
struct student
{
char sno[10];
char name[10];
int grade[3];
};
void write()
{
FILE *fp;
struct student s[10];
int i,j;
if((fp=fopen("test.txt","w"))==NULL)
{
printf("无法打开文件。\n");
exit(1);
}
printf("请输入数据:\n");
for(i=0;i<N;i++)
{
printf("请输入学号:");
scanf("%s",s[i].sno);
printf("请输入3门课的成绩:");
for(j=0;j<3;j++)
scanf("%d",&s[i].grade[j]);
printf("请输入姓名:");
scanf("%s",s[i].name);
}
for(i=0;i<N;i++)
fprintf(fp,"%s %s %d %d %d ",s[i].sno,s[i].name,s[i].grade[0],s[i].grade[1],s[i].grade[2]);
fclose(fp);
}
void read()
{
FILE *fp;
struct student s;
if((fp=fopen("test.txt","r"))==NULL)
{
printf("无法打开文件。\n");
exit(1);
}
printf("学号\t姓名\t语文\t数学\t英语\n");
while(fscanf(fp,"%s %s %d %d %d",s.sno,s.name,&s.grade[0],&s.grade[1],&s.grade[2])!=EOF)
{
printf("%-5s%-10s\t%4d\t%4d\t%4d\n",s.sno,s.name,s.grade[0],s.grade[1],s.grade[2]);
}
fclose(fp);
}
void main()
{
write();
read();
}