我想编写一个 C 程序来计算文本文件的单词。我使用下面的循环:
while (fscanf(fp, "%*s") != EOF ) {
count++;
}
fp
指向一个文本文件。这可能是fscanf()
功能有早期匹配失败?因为我认为它肯定会到达文件的末尾,所以!= EOF
.
最佳答案
您的程序应该按预期工作 fscanf(fp, "%*s")
返回 0
除了返回 EOF
的输入失败.除非您使输入流面向宽并且存在编码错误,否则输入失败应该只发生在文件结尾和读取错误上。fscanf(fp, "%*s")
永不返回 1
因为*
导致在返回值中忽略输入匹配,只有 已分配 计算转换后的值:
7.21.6.2 The
fscanf
function...
Returns
The
fscanf
function returns the value of the macroEOF
if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
这可以通过这个程序来验证:
#include <stdio.h>
int main() {
int res = scanf("%*s");
printf("scanf(\"%%*s\") -> %d\n", res);
return 0;
}
chqrlie$ ./scanf0 < /dev/null
scanf("%*s") -> -1
chqrlie$ echo 'test' | ./scanf0
scanf("%*s") -> 0
为了您的目的,您可以编写这个强调预期返回值的替代方案:while (fscanf(fp, "%*s") == 0) {
count++;
}
关于 `scanf("%*s")` 会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068392/