主题:以追加方式将一学生记录写入d:\stu2,然后输出所有数据。为何以下C程序运行后会出现说明中的问题?
#include<stdio.h>
#define ST struct student
#define N 3
ST
{char class[6];
long num;
char name[20];
int math,eng,comp;
}a[N],stu,b;
void main()
{int i;
FILE *fp;
fp=fopen("d:\\stu2","wb");
if(fp==NULL)
{printf("\n\n\t\tThe file can't be created.\n");
exit(1);
}
for(i=0;i<N;i++)
{printf("\n\tPlease input the class:"); scanf("%s",a[i].class);
printf("\n\tPlease input the number:"); scanf("%ld",&a[i].num);
printf("\n\tPlease input the name:"); scanf("%s",a[i].name);
printf("\n\tPlease input the math:"); scanf("%d",&a[i].math);
printf("\n\tPlease input the eng:"); scanf("%d",&a[i].eng);
printf("\n\tPlease input the comp"); scanf("%d",&a[i].comp);
}
if(fwrite(a,sizeof(ST),N,fp)!=N)
{printf("The data can't be write into the file,please check!\n");exit(1);}
fclose(fp);
fp=fopen("d:\\stu2","ab+");
printf("Please input the added data:\n");
scanf("%s%ld%s%d%d%d",b.class,&b.num,b.name,&b.math,&b.eng,&b.comp);
fwrite(&b,sizeof(ST),1,fp);
fclose(fp);
fp=fopen("d:\\stu2","rb");
if(fp!=NULL)
{printf("\n\tclass number name math eng comp\n");
while(feof(fp)==0)//为什么此处用for(i=0;i<N+1;i++)语句运行后不会出现"The file can't be read,please check!",用feof控制循环就会出现该提示?
{if(fread(&stu,sizeof(ST),1,fp)==1)
printf("\t%6s%10ld%9s%5d%6d%8d\n",stu.class,stu.num,stu.name,stu.math,stu.eng,stu.comp);
else
{printf("The file can't be read,please check!\n");
exit(1);
}
}
}
else{printf("File can't be opened.\n");exit(1);}
fclose(fp);
}
#define ST struct student
#define N 3
ST
{char class[6];
long num;
char name[20];
int math,eng,comp;
}a[N],stu,b;
void main()
{int i;
FILE *fp;
fp=fopen("d:\\stu2","wb");
if(fp==NULL)
{printf("\n\n\t\tThe file can't be created.\n");
exit(1);
}
for(i=0;i<N;i++)
{printf("\n\tPlease input the class:"); scanf("%s",a[i].class);
printf("\n\tPlease input the number:"); scanf("%ld",&a[i].num);
printf("\n\tPlease input the name:"); scanf("%s",a[i].name);
printf("\n\tPlease input the math:"); scanf("%d",&a[i].math);
printf("\n\tPlease input the eng:"); scanf("%d",&a[i].eng);
printf("\n\tPlease input the comp"); scanf("%d",&a[i].comp);
}
if(fwrite(a,sizeof(ST),N,fp)!=N)
{printf("The data can't be write into the file,please check!\n");exit(1);}
fclose(fp);
fp=fopen("d:\\stu2","ab+");
printf("Please input the added data:\n");
scanf("%s%ld%s%d%d%d",b.class,&b.num,b.name,&b.math,&b.eng,&b.comp);
fwrite(&b,sizeof(ST),1,fp);
fclose(fp);
fp=fopen("d:\\stu2","rb");
if(fp!=NULL)
{printf("\n\tclass number name math eng comp\n");
while(feof(fp)==0)//为什么此处用for(i=0;i<N+1;i++)语句运行后不会出现"The file can't be read,please check!",用feof控制循环就会出现该提示?
{if(fread(&stu,sizeof(ST),1,fp)==1)
printf("\t%6s%10ld%9s%5d%6d%8d\n",stu.class,stu.num,stu.name,stu.math,stu.eng,stu.comp);
else
{printf("The file can't be read,please check!\n");
exit(1);
}
}
}
else{printf("File can't be opened.\n");exit(1);}
fclose(fp);
}