提问人:StackUser 提问时间:7/26/2015 最后编辑:StackUser 更新时间:7/26/2015 访问量:387
使用 fscanf [duplicate] 读取文件时丢失数据
losing data when reading a file with fscanf [duplicate]
问:
使用如下代码的一部分:
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));
}
答:
3赞
Michael Karcher
7/26/2015
#1
将 fscanf 放在循环的末尾。FScanf 读取,直到确定数字完成。如果输入文件的最后一个字符是数字(与空格或换行符相对),则在解析最后一行时(有些人会将不以换行符结尾的行称为“不完整的最后一行”),fscanf 会命中 EOF 试图找到数字的末尾,因此 feof 为 true,因为 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.
评论
0赞
StackUser
7/26/2015
请问,你能写一部分代码来更好地解释吗?谢谢
1赞
Spikatrix
7/26/2015
我现在没有要测试的 PC,但是在您提供的示例代码中,第三个不应该返回 -1() 吗?fscanf
EOF
0赞
Michael Karcher
7/26/2015
@CoolGuy 感谢您的更正,已编辑。
上一个:php - feof 错误
下一个:错误:在“!”令牌之前应为“)”
评论