#include<stdio.h>
#include<stdlib.h>
#define M 6
#define N 3
struct student{
int num;
char name[20];
float score[3];
float ave;
}cla1[M+1],cla2[M+1],temp,st1;
//从文件中读取学生信息,按照平均分插入学生节点
void main(){
FILE *fp;
int i,j;
float ave = 0;
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");
}
fclose(fp);
printf("请输入需要插入的学生节点数据:\n");
scanf("%d,%s",&st1.num,st1.name);
for(j = 0;j < N;j++){
scanf("%f",&st1.score[j]);
ave += st1.score[j];
}
st1.ave = ave/N;
cla1[M] = st1;
for(i = 0;i < M;i++)
for(j = i+1;j < M+1;j++)
if(cla1[i].ave < cla1[j].ave){
temp = cla1[i];
cla1[i] = cla1[j];
cla1[j] = temp;
}
if((fp = fopen("stu_sort","wb")) == NULL){
printf("error 202!\n");
exit(0);
}
for(i = 0;i <= M;i++)
fwrite(&cla1[i],sizeof(struct student),1,fp);
fclose(fp);
if((fp = fopen("stu_sort","rb")) == NULL){
printf("error 203!\n");
exit(0);
}
for(i = 0;i <= M;i++)
fread(&cla2[i],sizeof(struct student),1,fp);
fclose(fp);
printf("插入后的数据:\n");
for(i = 0;i <= M;i++){
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");
}
}
从文件中读取学生信息,按照平均分顺序插入学生节点,保存到原文件中
最新推荐文章于 2024-06-01 18:29:03 发布