gpt4 book ai didi

c - fgetc() : Is it enough to just check EOF?

转载 作者:太空狗 更新时间:2023-10-29 16:59:17 25 4
gpt4 key购买 nike

在网上找到的各种例子中,fgetc()是这样使用的:

FILE *fp = fopen(PATH, "r");

if (fp == NULL) {
perror("main");
exit(EXIT_FAILURE);
}

int ch;

while (ch = fgetc(fp) != EOF) {
// do something
}

但是根据 fgetc() 的联机帮助页

If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, [CX] and shall set errno to indicate the error.

所以我也需要检查这个吗?以及如何?

最佳答案

规范是这样说的:

the fgetc() function shall obtain the next byte as an unsigned char converted to an int

The following macro name shall be defined as a negative integer constant expression: EOF

只要您将返回值存储在 int 而不是 char 中,检查 EOF 就足够了,因为它是保证不代表有效的字符值。


此外,在您的代码中,这是:

while (ch = fgetc(fp) != EOF)

应该是:

while ((ch = fgetc(fp)) != EOF)

额外的括号是必需的,因为 != 的优先级高于 =

关于c - fgetc() : Is it enough to just check EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4292729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com