#include<stdio.h>
#include<stdlib.h>
#define M 6
#define N 3
struct student{
int num;
char name[20];
float score[3];
float ave;
}cla2[M],cla1[M],st1;
void main(){
FILE *fp;
int i,j;
if((fp = fopen("stu","rb")) == NULL){
printf("ERROR 201!\n");
exit(0);
}
printf("排序之前的数据:\n");
for(i = 0;i < M;i++){
fread(&cla2[i],sizeof(struct student),1,fp);
printf("%-5d,%-7s",cla2[i].num,cla2[i].name);
for(j = 0;j < N;j++)
printf("%-6.2f",cla2[i].score[j]);
printf("%-6.2f",cla2[i].ave);
printf("\n");
}
fclose(fp);
for(i = 0;i < M-1;i++)
for(j = i+1;j < M;j++)
if(cla2[i].ave < cla2[j].ave){
st1 = cla2[i];
cla2[i] = cla2[j];
cla2[j] = st1;
}
if((fp = fopen("stu_sort","wb")) == NULL){
printf("ERROR 202!\n");
exit(0);
}
for(i = 0;i < M;i++){
fwrite(&cla2[i],sizeof(struct student),1,fp);
}
fclose(fp);
if((fp = fopen("stu_sort","rb")) == NULL){
printf("ERROR 201!\n");
exit(0);
}
printf("排序之后的数据:\n");
for(i = 0;i < M;i++){
fread(&cla1[i],sizeof(struct student),1,fp);
printf("%-5d,%-7s",cla1[i].num,cla1[i].name);
for(j = 0;j < N;j++)
printf("%-6.2f",cla1[i].score[j]);
printf("%-6.2f",cla1[i].ave);
printf("\n");
}
}
从文件中读取学生信息,排序后存放到新的文件stu_sort中
最新推荐文章于 2019-12-11 23:33:32 发布