编写程序,求第5题中每个学生的总分和平均分,并给学生数据增加上总分和平均分,文件名为stu2.dat。
#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;
float ave,num;
struct student stu[N];
if((fp1=fopen("stu2.dat","w"))==NULL)
{
printf("File open error");
exit(0);
}
if((fp2=fopen("D:\\codeblock\\shiyanyiwenjian5\\stu1.dat","r"))==NULL)
{
printf("File open error");
exit(0);
}
for(i=0; i<N; i++)
{
fscanf(fp2,"%d",&stu[i].num);
fgetc(fp2);//fgetchar吞空格,避免把空格当成%s%c
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);
num=(stu[i].chinese+stu[i].math+stu[i].pe);
ave=num/3.0;
fprintf(fp1,"%d\t%s\t%c\t %d\t%d\t%d\t %lf\t%lf\n",stu[i].num,stu[i].name,stu[i].sex,stu[i].chinese,stu[i].math,stu[i].pe,num,ave);
}
if(fclose(fp1))
{
printf("Can not close file");
}
if(fclose(fp2))
{
printf("Can not close file");
}
return 0;
}