使用fscanf读取文件时丢失数据

时间:2015-07-26 08:57:50

标签: c file eof scanf feof

使用如下代码的一部分:

fscanf(f1, "%d", &n);
while(!feof(f1)){
...
fscanf(f1, "%d", &n);}

它错过了文件的最后一行(符合EOF)。我该怎么解决?

我找到的唯一解决方案是:

if (fscanf(f1, "%d", &n)!=EOF){
rewind(f1);
do{
...
fscanf(f1, "%d", &n);
}while(!feof(f1));
}

1 个答案:

答案 0 :(得分:3)

你把fscanf放在循环的末尾。 fscanf读取,直到确定数字完成。如果输入文件的最后一个字符是一个数字(与空格或新行相对),则在解析最后一行时(有些人会调用一行不在换行符中“不完整的最后一行”),fscanf会尝试EOF尝试找到数字的结尾,所以feof是真的,因为EOF已被击中。

你不应该检查feof,而是检查fscanf的返回码。它会告诉您是否有一些数字可以解析为数字。

假设您的文件包含"11\n23"

f = fopen(...);
result = fscanf(f, "%d", &i);
// result == 1, because one variable has been read
// i == 11, because that's the first number
// file pointer is past the '\n', because '\n'
//   had to be read to find out the number is not
//   something like 110
//   The '\n' itself has been put back using ungetc
// feof(f) == 0, because nothing tried to read past EOF

result = fscanf(f, "%d", &i);
// result == 1, because one variable has been read by this call
// i == 23 (obviously)
// file pointer is at EOF (it can't go further)
// feof(f) == 1, because fscanf tried to read past
//   the '3' to check whether there were extra
//   characters.

//  (Your loop terminates here, because feof(f) is true

result = fscanf(f, "%d", &i);
// result == EOF (error before first variable)
// i is likely unchanged. I am unsure whether this
//   is guaranteed by the language definition
// file pointer unchanged
// feof(f) still true

// You should terminate processing *NOW*, because
// return is no longer one.