struct rec{
char name[15];
int average;
};
int input(struct rec *p){
char ch ='y';
int count=0;
while(ch!='n'){
printf("name : ");
scanf("%s",p->name);
printf("ave : ");
scanf("%d",&p->average);
fflush(stdin);
ch=getchar();
count+=1;
p++;
}
return count;
}
void display(struct rec *p,int n){
for(int i=0;i<n;i++){
printf("name : %s\n",p->name);
printf("average: %d\n",p->average);
p++;
}
}
int main()
{
FILE *f;
struct rec p,t[10];
int n;
n=input(&t);
f=fopen("t.dat","wb");
for(int i=0;i<n;i++)
fwrite(&t[i],sizeof(struct rec),1,f);
fclose(f);
f=fopen("t.dat","rb");
while(!feof(f)){
fread(&p,sizeof(struct rec),1,f);
display(&p,1);
if(feof(f)){
break;
}}
}
输入:
name : kesh
ave : 88
y
name : ridha
ave : 99
y
name : shri
ave : 89
n
输出:
name : kesh
average: 88
name : ridha
average: 99
name : shri
average: 89
name : shri
average: 89
我不明白为什么文件中的最后一个结构被打印两次?