将第5题“stud”文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件“stu_sort“中。
第5题内容:有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据(包括学号、姓名、三门课的成绩),计算出平均成绩,将原有数据和计算出平均分数存放在磁盘文件“stud”中 。
解法1【c源程序】
#include
#include
#define N 10
struct student
{char num[10];
char name[8];
int score[3];
float ave;
} st[N],temp;
int main()
{FILE *fp;
int i,j,n;
/*读文件*/
if ((fp=fopen("stud","r"))==NULL)
{printf("can not open.\n");
exit(0);
}
printf("File 'stud': ");
for (i=0;fread(&st[i],sizeof(struct student),1,fp)!=0;i++)
{printf("\n%8s%8s",st[i].num,st[i].name);
for (j=0;j<3;j++)
printf("%8d",st[i].score[j]);
printf("%10.2f",st[i].ave);
}
printf("\n");
fclose(fp);
n=i;
/*排序*/
for (i=0;i
for (j=i+1;j
if (st[i].ave < st[j].ave)
{temp=st[i];
st[i]=st[j];
st[j]=temp;
}
/*输出*/
printf("\nNow:");
fp=fopen("stu_sort","w");
for (i=0;i
{fwrite(&st[i],sizeof(struct student),1,fp);
printf("\n%8s%8s",st[i].num,st[i].name);
for (j=0;j<3;j++)
printf ("%8d",st[i].score[j]);
printf("%10.2f",st[i].ave);
}
printf("\n");
fclose(fp);
return 0;
}
解法2【c源程序】
#include
#include
#define SIZE 5
struct student
{
char name[10];
int num;
int score[3];
float ave;
} stud[SIZE],work;
int main()
{
void sort(void);
int i;
FILE *fp;
sort();
fp=fopen("stud_sort.dat","rb");
printf("sorted student's scores list as follow\n");
printf("----------------------------------------------------\n");
printf(" NAME N0. SCORE1 SCORE2 SCORE3 AVE \n");
printf("----------------------------------------------------\n");
for (i=0;i
{
fread(&stud[i],sizeof(struct student),1,fp);
printf("%-10s %3d %8d %8d %8d %9.2f\n",stud[i].name,stud[i].num,
stud[i].score[0],stud[i].score[1],stud[i].score[2],stud[i].ave);
}
fclose(fp);
return 0;
}
void sort(void)
{FILE *fp1,*fp2;
int i,j;
if ((fp1=fopen("stu.dat","rb"))==NULL)
{printf("The file can not open\n\n");
exit(0);
}
if ((fp2=fopen("stud_sort.dat","wb"))==NULL)
{printf("The file write error\n");
exit(0);
}
for (i=0;i
if (fread(&stud[i],sizeof(struct student),1,fp1)!=1)
{printf("file read error\n");
exit(0);
}
for (i=0;i
{for (j=i+1;j
if (stud[i].ave
{work=stud[i];
stud[i]=stud[j];
stud[j]=work;
}
fwrite(&stud[i],sizeof(struct student),1,fp2);
}
fclose(fp1);
fclose(fp2);
}