编写程序,建立一个含有N名(N≤5)学生成绩的文件:stu1.dat,每个学生的数据包括:学号、姓名、性别(如下图所示,内容可以简略表示为’M’,或’F’)、语文、数学、体育。
#include <stdio.h>
#include <stdlib.h>
#define N 5
struct student{
int num;
char name[10];
char sex;
int chinese;
int math;
int pe;
};
int main()
{ FILE *fp1,*fp2;
int i,n;
struct student stu[N];
if((fp1=fopen("stu1.dat","w"))==NULL)
{
printf("File open error");
exit(0);
}
if((fp2=freopen("f2.dat","r",stdin))==NULL)
{
printf("File open error");
exit(0);
}
for(i=0;i<N;i++)
{fscanf(fp2,"%d",&stu[i].num);
fgetc(fp2);
fscanf(fp2,"%s",stu[i].name);
fgetc(fp2);
fscanf(fp2,"%c",&stu[i].sex);
fscanf(fp2,"%d",&stu[i].chinese);
fscanf(fp2,"%d",&stu[i].math);
fscanf(fp2,"%d",&stu[i].pe);
fprintf(fp1,"%d\t%s\t%c\t%d\t%d\t%d\n",stu[i].num,stu[i].name,stu[i].sex,stu[i].chinese,stu[i].math,stu[i].pe);
}
if(fclose(fp1))
{
printf("Can not close file");
}
if(fclose(fp2))
{
printf("Can not close file");
}
return 0;
}