`scanf("%*s")` 会失败吗?

标签 c

我想编写一个 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 macro EOF 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/

相关文章:

cgo 使用 c struct 数组并在 go 中赋值

c - 未定义对 `_fcloseall' 的引用

c - 系统小程序 : Assertion failed - How can I solve?

c++ - 文件夹大小 linux

c - 如何使用 gcc 打印 __uint128_t 数字?

Char 二维指针数组

c - 在 C 中编译 Lisp 解释器时收到警告

在 Arduino Due 上使用 contikiOS 进行 C 或 C++ 编程

c - 从 C 中的用户输入分配结构内部的数组大小

c - 使用 gdb 调试 C 代码