编写程序,建立一个含有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;
}


该程序使用C语言实现,创建一个名为stu1.dat的文件,存储不超过5名学生的基本信息和成绩,包括学号、姓名、性别(用'M'或'F'表示)、语文、数学和体育成绩。程序从标准输入读取数据,并将其格式化写入到stu1.dat文件中。
1828

被折叠的 条评论
为什么被折叠?



