2014-04-20 196 views
6

我有以下简单的程序可以从文本文件(num.txt)中读取。该文本文件在每行中都有数字1 2 3 4 5。当我运行该程序时,它会打印5次两次。有人可以告诉我为什么会发生这种情况,以及如何解决这个问题?在此先感谢fscanf读取最后的整数两次

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

+0

'而(!FEOF(文件)){':: FEOF()是问题 – wildplasser

+3

我建议你阅读[这](事业http://stackoverflow.com/questions/5431941/同时,FEOF文件 - 是 - 总是错的)? – niklasfi

+1

当你看到最后5个时,fscanf返回的值是多少?我打赌它不是1. ;-) –

回答

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; 
} 
4

失败第二次fscanf并没有写任何东西给number,这就是为什么它仍然是5最后一次。要知道fscanf是否成功,您必须检查其返回值。

fscanf返回它写入的参数个数。在你的情况下,如果它返回1,它就起作用了;如果它返回0,它没有。这是你应该检查而不是feof。如果前 所述第一转换成功或匹配失败时达到输入结束则返回

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