回 帖 发 新 帖 刷新版面

主题:以追加方式将一学生记录写入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);
}

回复列表 (共1个回复)

沙发

先弄清楚feof的作用。
这个函数的作用是“检查是否遇到了文件结束符”。如果是,返回1,否则返回0。

然后看代码:
while (feof(fp) == 0)
{
  if (fread(...) == 1)
  {
  }
  else
  {
    printf("The file can't be read,please check!\n");
  }
}

假设文件中总共有5条数据,则循环5次之后,正好到达文件结尾。但注意,到现在为止,读取的所有数据都是正常数据,并没有遇到“文件结束符”。因此feof仍然返回0,条件成立,因此继续循环。于是又执行了fread,这时没有数据可读,于是失败了。
补充说明:读完所有数据之后,再进行读取,才会遇到所谓的“文件结束符”,此时feof才会返回1。
用for (i=0; i<N+1; i++)不会有上述问题。

我来回复

您尚未登录,请登录后再回复。点此登录或注册