fscanf读取最后一个整数两次

时间:2014-04-20 17:40:59

标签: c file-io

我有一个简单的程序可以从文本文件(num.txt)中读取。文本文件的每行数字为1 2 3 4 5。当我运行程序时,它会打印5次。任何人都能告诉我为什么会发生这种情况,以及如何解决这个问题?提前谢谢

int main(void)
{
   int number;
   FILE *file;

   int i = 0;;

   file = fopen("num.txt", "r");

   while (!feof(file)){

      fscanf(file, "%d", &number);
      printf("%d\n", number);
      }

   return 0;
}

这是我的文本文件num.xtx

1
2
3
4
5

这是程序输出

1
2
3
4
5
5

还有额外的5

2 个答案:

答案 0 :(得分:7)

scanf函数系列的手册页

  

如果之前到达输入结尾,则返回值EOF   要么是第一次成功转换,要么是匹配失败。   如果发生读取错误,也会返回EOF,在这种情况下会出现错误   设置流的指示符,并设置errno以指示   错误。

这意味着上一次成功的fscanf调用会从流file中读取最后一行,之后while循环条件!feof(file)为真,因为文件结束条件还没有实现。这意味着循环执行一次额外的时间,并再次打印变量number的先前值。

请阅读此内容 - while(!feof(file)) is always wrong

您应该检查scanf的返回值,而不是检查文件流上的文件结束指示符。

#include <stdio.h>   

int main(void) {
   int number;
   FILE *file = fopen("num.txt", "r");

   // check file for NULL in case there
   // is error in opening the file
   if(file == NULL) {
      printf("error in opening file\n");
      return 1;
   }      

   // check if fscanf call is successful 
   // by checking its return value for 1.
   // fscanf returns the number of input
   // items successfully matched and assigned
   while(fscanf(file, "%d", &number) == 1)
      printf("%d\n", number);

   return 0;
}

答案 1 :(得分:5)

第二次fscanf失败并且没有向number写任何内容,这就是为什么它最后一次仍为5的原因。要知道fscanf是否成功,您必须检查其返回值。

fscanf返回它写入的参数数量。在你的情况下,如果它返回1,它工作;如果它返回0,它就没有了。这是您应该检查的,而不是feof

while (fscanf(file, "%d", &number) == 1)
{
    printf("%d\n", number);
}
相关问题