#include<stdio.h>
#include<stdlib.h>
#define N 5
struct stu
{
int stunum;
char name[20];
float score[3];
float aver;
}s[N];
int main()
{
FILE *fp;
int i;
void order(struct stu s[]);
void save();
void print();
if((fp=fopen("stu_sort.txt","rb"))==NULL)
{
printf("Cannot open!\n");
exit(0);
}
for(i=0;i<N;i++)
{
fread(&s[i],sizeof(struct stu),1,fp);
printf("%d %s %.0f %.0f %.0f %.2f\n",s[i].stunum,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],s[i].aver);
}
fclose(fp);
printf("请输入要插入的数据:\n");
scanf("%d %s %f %f %f",&s[N].stunum,&s[N].name,&s[N].score[0],&s[N].score[1],&s[N].score[2]);
s[N].aver=(s[N].score[0]+s[N].score[1]+s[N].score[2])/3.0;
order(s);
if((fp=fopen("stu_new.txt","wb"))=NULL)
{
printf("Cannot open!\n");
exit(0);
}
for(i=0;i<N+1;i++)
{
fwrite(&s[i],sizeof(struct stu),1,fp);
}
save();
fclose(fp);
printf("插入后的为:\n");
print();
return 0;
}
void order(struct stu s[])
{
int i,j;
struct stu t;
for(i=0;i<N;i++)
{
for(j=0;j<N-i;j++)
{
if(s[j].aver >s[j+1].aver )
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
}
void save()
{
FILE *fp;
int i;
if((fp=fopen("stu_new.txt","wb"))==NULL)
{
printf("Cannot open!\n");
return;
}
for(i=0;i<N+1;i++)
{
if(fwrite(&s[i],sizeof(struct stu),1,fp)!=1)
printf("File with error!\n");
}
fclose(fp);
}
void print()
{
FILE *fp;
int i;
if((fp=fopen("stu_new.txt","rb"))==NULL)
{
printf("Cannot open!\n");
return;
}
for(i=0;i<N+1;i++)
{
fread(&s[i],sizeof(struct stu),1,fp);
printf("%d %s %.0f %.0f %.0f %.2f\n",s[i].stunum,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],s[i].aver);
}
}