回 帖 发 新 帖 刷新版面

主题:[讨论]一个关于读取文件内容的困惑

while(!feof(stu_information)) 
{
 test=(struct student*)malloc(sizeof(struct student));
 if(num==1)
  head=operation=test;
 else 
  operation->next=test;
  operation=test;
  fscanf(stu_information,"%d%s%s%d",&operation->numble,operation->name,operation->sex,&operation->age);
  num++;
  
}
  operation->next=NULL;
  operation=head;
  while(operation!=NULL)
  {
    printf("%d  %s  %s  %d\n",operation->numble,operation->name,operation->sex,operation->age);
    operation=operation->next;

  }
    fclose(stu_information);
}

想请教一下就是若在文件stu_information里有两组结构体数据为什么这个函数会循环三次,就是会多读取一次数据而导致多开辟了一个空间导致最后一组数据是乱码啊

回复列表 (共4个回复)

沙发

看到 while(!feof(stu_information)) 这种代码,不说100%,起码99%可以肯定是错误的。
先把 feof 的含义弄清楚嘛

板凳

csdn见到同样问题。。哎、、

3 楼

为什么while(!feof(stu_information))是错的,这个不是用来判断文件是否结束的函数吗

4 楼

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
  const char * fname = "foo";
  FILE       * fp;

  { // 写入数据
    fp = fopen (fname, "wb");
    fprintf (fp, "1234");
    fclose (fp);
    puts ("写入4个字符,\"1234\"");
  }

  { // 读取数据
    int count, char_;
    fp = fopen (fname, "rb");
    for (count = 0; !feof(fp); )
      {
        ++count;
        char_ = fgetc (fp);
        printf ("<%0#10X:%c>\n", (unsigned)char_, (char)char_);
      }
    fclose (fp);
    printf ("读取%d次", count);
  }
  
  return 0;
}
根据上面的代码,发现 当文件fp读取完最后一个字符以后,feof(fp)将还是返回0(还没到EOF).然后再用fgetc函数从文件fp中读取一个字符,将得到(-1).在这以后,feof(fp)才会返回 非0. 也就是说,feof函数只能判断 一个文件已经到达了 EOF,而不是 即将要到达EOF(文件的最后一个字符已被读取完)。

我来回复

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