C语言读取文件的内容计算平均分并输出

问:输入五个学生的信息,并写入data2.txt文件中。读取文件data2.txt的内容,计算平均分并输出。
#include <stdio.h>
#include <stdlib.h>
struct student
{
char sex;
char name[8];
char sno[20];
int age;
double score;
};
int main()
{
FILE *fp;
double avg,sum=0;
int i;
struct student Student[5];
fp=fopen("D:\\CC\\data2.txt","w");
puts("input the information of 5 students:");
for(i=0;i<5;i++)
scanf("%c%s%s%d%lf",&Student[i].sex,Student[i].name,Student[i].sno,&Student[i].age,&Student[i].score);
for(i=0;i<5;i++)
fprintf(fp,"%2c %s %s %2d %2f\n",Student[i].sex,Student[i].name,Student[i].sno,Student[i].age,Student[i].score);
fclose(fp);
fp=fopen("D:\\CC\\data2.txt","r");
if((fp=fopen("D:\\CC\\data2.txt","r"))==NULL)
{
printf("Can't open the file!\n");
exit(0);
}
for(i=0;i<5;i++)
{
fseek(fp,i*sizeof(struct student),0);
if(fread(&Student[i],sizeof(struct student),1,fp)!=1)
printf("Can't execute the file.'fread' error!\n");
sum+=Student[i].score;
}
avg=sum/5;
puts("calculate the average of all students:");
printf("The average of the five students is %2f\n",avg);
fclose(fp);
return 0;
}
错在哪?

试一下以下代码
#include <stdio.h>
#include <stdlib.h>
struct student
{
char sex;
char name[8];
char sno[20];
int age;
double score;
};
int main()
{
FILE *fp;
double avg,sum=0;
int i;
struct student Student[5];
//fp=fopen("D:\\CC\\data2.txt","w");
fp=fopen("data2.txt","w");
if ( fp==NULL )
{
printf("open file for read error\n");
return -1;
}
puts("input the information of 5 students:");
for(i=0;i<5;i++)
scanf("%c%*c%s%s%d%lf",&Student[i].sex,Student[i].name,Student[i].sno,&Student[i].age,&Student[i].score);//
for(i=0;i<5;i++)
fprintf(fp,"%c %s %s %2d %2f\n",Student[i].sex,Student[i].name,Student[i].sno,Student[i].age,Student[i].score);
fclose(fp);
//fp=fopen("D:\\CC\\data2.txt","r");
fp=fopen("data2.txt","r");
if(fp==NULL)
{
printf("Can't open the file!\n");
exit(0);
}
for(i=0;i<5;i++)
{
fscanf(fp, "%c%*c%s%s%d%lf",&Student[i].sex,Student[i].name,Student[i].sno,&Student[i].age,&Student[i].score); //
sum+=Student[i].score;
}
avg=sum/5;
puts("calculate the average of all students:");
printf("The average of the five students is %2f\n",avg);
fclose(fp);
return 0;
}

追问

程序的运行情况及结果 后面的 sno name等等

追答

刷一下页面,看我补充的代码,先试试

追问

看到
fseek(fp,i*sizeof(struct student),0);
if(fread(&Student[i],sizeof(struct student),1,fp)!=1)
printf("Can't execute the file.'fread' error!\n");
sum+=Student[i].score;
运行一下 确实正确了 请问一下为什么上面是错误的?

追答

用fprintf()写到文件中的数据,就要用fscanf()函数来读取!
fread()对应的写文件,应该是fwrite()函数!
而且,你没有必要每次调用fseek()函数来定位,函数在读一次后,后自动移动文件指针!

温馨提示:答案为网友推荐,仅供参考
相似回答