/**********************头文件*************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
/*
有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据【姓名,学号,3门课成绩】,计算平均成绩,将原有
数据和计算的平均分数存放磁盘文件stud.dat中
*/
/*************************学生结构体*******************************************************************/
//定义结构体描述学生的信息
struct student
{
char name[10];
int num;
int score[3];
float ave;
}stud[SIZE];//定义结构体数组stud
/********************************主函数********************************************************************/
int main()
{
void save(void);//声明save函数
int i;
float sum[SIZE];
FILE *fp1;//定义fp1指针文件
for (i = 0; i < SIZE; i++)
{
scanf("%s %d %d %d %d", stud[i].name, &stud[i].num, &stud[i].score[0], &stud[i].score[1], &stud[i].score[2]);
sum[i] = stud[i].score[0] + stud[i].score[1] + stud[i].score[2];
stud[i].ave = sum[i] / 3;
}
save();//调用save函数
fp1 = fopen("stu.dat", "rb");
printf("\n name NO. score1 score2 score3 ave\n");
printf("---------------------------------------------------------\n");
for (i = 0; i < SIZE; i++)
{
fread(&stud[i], sizeof(struct student), 1, fp1);
printf("%-10s %3d %7d %7d %7d %8.2f\n", stud[i].name, stud[i].num, stud[i].score[0], stud[i].score[1], stud[i].score[2], stud[i].ave);
}
fclose(fp1);//关闭文件fp1
return 0;
}
/********************************************************************************************************************************************/
/********************save函数进行保存数据****************************************************************************************************/
void save(void)
{
FILE *fp;//定义指针文件fp
int i;
if ((fp = fopen("stu.dat","wb")) == NULL)//打开文件
{
printf("the file can not open\n");
return;
}
for(i=0;i<SIZE;i++)//进行写入
if (fwrite(&stud[i], sizeof(struct student), 1, fp) != 1)
{
printf("the file write error\n");
return;
}
fclose(fp);
}
/*********************************************************************************************************************************************/