对文件存贮结构体变量的一些操作记录及几个错误解决
做到第十三章的文件题,做一些记录。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3
typedef struct student
{
int num;
char name[10];
float score[3];
float ave;
}BT;
void main()
{
FILE *fp,*fp1;
BT s[N],s1[N],s3[N+1],s4[N+1],temp;
int i,j,n;
if((fp=fopen("file","w+"))==0)
{
printf("cannot open file\n");
exit(0);
}
if((fp1=fopen("file1","w+"))==0)
{
printf("cannot open file\n");
exit(0);
}
printf("请输入三个学生信息:\n");
for(i=0;i<N;i++)
scanf("%d%s%f%f%f",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2]);
for(i=0;i<N;i++)
s[i].ave=(s[i].score[0]+s[i].score[1]+s[i].score[2])/3;
for(i=0;i<N;i++)
if(fwrite(&s[i],sizeof(struct student),1,fp)!=1)
printf("file write error\n");
rewind(fp);
for(i=0;i<N;i++)
if(fread(&s1[i],sizeof(struct student),1,fp)!=1)
printf("read write error\n");
for(i=0;i<N-1;i++)
for(j=i+1;j<N;j++)
if(s1[i].ave>s1[j].ave)
{
temp=s1[i];
s1[i]=s1[j];
s1[j]=temp;
}
for(i=0;i<N;i++)
if(fwrite(&s1[i],sizeof(struct student),1,fp1)!=1)
printf("file write error\n");
rewind(fp1);
for(i=0;i<N;i++)
if(fread(&s3[i],sizeof(struct student),1,fp1)!=1)
printf("file read error\n");
printf("请输入第N+1个学生的数据:\n");
scanf("%d%s%f%f%f",&s3[N].num,s3[N].name,&s3[N].score[0],&s3[N].score[1],&s3[N].score[2]);
s3[N].ave=(s3[N].score[0]+s3[N].score[1]+s3[N].score[2])/3;
for(i=0;i<N+1;i++)
printf("%d %s %.2f %.2f %.2f %.2f\n",s3[i].num,s3[i].name,s3[i].score[0],s3[i].score[1],s3[i].score[2],s3[i].ave);
for(i=0;i<N;)
{
if(s3[0].ave>s3[N].ave)
{
i=0;
break;
}
else if(s3[i++].ave<=s3[N].ave&&s3[i].ave>=s3[N].ave)
break;
else if(s3[N-1].ave<s3[N].ave)
{
i=N;break;
}
}
printf("i=%d\n",i);
n=i;
fseek(fp1,n*sizeof(struct student),0);
if(fwrite(&s3[N],sizeof(struct student),1,fp1)!=1)
printf("file write error\n");
for(i=n;i<N;i++)
if(fwrite(&s3[i],sizeof(struct student),1,fp1)!=1)
printf("file write error\n");
rewind(fp1);
for(i=0;i<N+1;i++)
if(fread(&s4[i],sizeof(struct student),1,fp1)!=1)
printf("file read error\n");
printf("\n\n");
for(i=0;i<N+1;i++)
printf("%d %s %.2f %.2f %.2f %.2f\n",s4[i].num,s4[i].name,s4[i].score[0],s4[i].score[1],s4[i].score[2],s4[i].ave);
fclose(fp);
fclose(fp1);
system("pause");
}