要求:
有5个学生,每个学生有3门课成绩,从键盘输入学生数据(包括姓名,学号,3门课成绩),计算出平均成绩,将原有数据和计算出的平均分数放在磁盘文件“file1.c”中。
分析:
先定义一个结构体数组student_type stud[SIZE],SIZE=5,来存储学生成绩及相关信息。首先向结构体数组元素依次输入学生相关信息,接着利用fwrite()函数将结构体数组信息写进磁盘文件“file1.c”中,为了更好地显示输入的信息,这里增加了磁盘文件读取部分,利用fread()函数将读取到信息存储在结构体数组student_type stud1[SIZE]中,并显示在终端屏幕上。
程序如下:
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
struct student_type{
char name[15]; //姓名
int num; //学号
float score[3]; //三门课成绩
float ave; //平均分数
}stud[SIZE],stud1[SIZE];
int main()
{
FILE *fp;
int i,j;
float sum=0;
if((fp=fopen("file1.c","wb"))==NULL)
{
printf("cannot open the file!");
exit(0);
}
for(i=0;i<SIZE;i++)
scanf("%s%d%f%f%f",stud[i].name,&stud[i].num,&stud[i].score[0],&stud[i].score[1],&stud[i].score[2]);
for(i=0;i<SIZE;i++)
{
sum=0;
for(j=0;j<3;j++)
sum=sum+stud[i].score[j];
stud[i].ave=sum/3;
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error!");
}
fclose(fp);
fp=fopen("file1.c","rb");
if(fp==NULL)
{
printf("cannot open the file!");
exit(0);
}
printf("从file1.c文件中读取到的信息如下:\n");
printf("姓名 学号 成绩1 成绩2 成绩2 平均分数\n");
for(i=0;i<SIZE;i++)
{
fread(&stud1[i],sizeof(student_type),1,fp);
printf("%s %d %f %f %f %f\n",stud1[i].name,stud1[i].num,stud1[i].score[0],stud1[i].score[1],stud1[i].score[2],stud1[i].ave);
}
fclose(fp);
return 0;
}
运行结果如下: