gpt4 book ai didi

c - getc() 是在返回 EOF 后定义的吗?

转载 作者:太空狗 更新时间:2023-10-29 15:22:50 24 4
gpt4 key购买 nike

我在 C 练习中使用了 getc();,回顾程序后我发现了一些奇怪的东西。我假设命令行参数中给出的文件至少包含一个字节。 (它连续两次调用 getc(); 而不检查 EOF。在一个空文件上尝试后它仍然运行顺利。我的问题是:getc(); 对已耗尽(已到达 EOF 且未倒带)的文件指针的行为未定义,还是会始终继续返回 EOF?

我想我可以将这个问题扩展到 C STL 中的所有 I/O 函数,请在您的回答中也说明这一点。

这是程序的代码。该程序应该从所有注释中删除 C/C++ 源文件(并且它运行良好)。

#include <stdio.h>

int main(int argc, char *argv[]) {
int state = 0; // state: 0 = normal, 1 = in string, 2 = in comment, 3 = in block comment
int ignchar = 0; // number of characters to ignore
int cur, next; // current character and next one
FILE *fp; // input file

if (argc == 1) {
fprintf(stderr, "Usage: %s file.c\n", argv[0]);
return 1;
}

if ((fp = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Error opening file.\n");
return 2;
}

cur = getc(fp); // initialise cur, assumes that the file contains at least one byte
while ((next = getc(fp)) != EOF) {
switch (next) {
case '/':
if (!state && cur == '/') {
state = 2; // start of comment
ignchar = 2; // don't print this nor next char (//)
} else if (state == 3 && cur == '*') {
state = 0; // end of block comment
ignchar = 2; // don't print this nor next char (*/)
}
break;
case '*':
if (!state && cur == '/') {
state = 3; // start of block comment
ignchar = 2; // don't print this nor next char (/*)
}
break;
case '\n':
if (state == 2) {
state = 0;
ignchar = 1; // don't print the current char (cur is still in comment)
}
break;
case '"':
if (state == 0) {
state = 1;
} else if (state == 1) {
state = 0;
}
}

if (state <= 1 && !ignchar) putchar(cur);
if (ignchar) ignchar--;
cur = next;
}

return 0;
}

最佳答案

Stdio 文件保留一个“eof”标志,该标志在第一次到达文件末尾时设置,并且只能通过调用 clearerr 或执行成功的 fseek 来重置或 倒带。因此,一旦 getc 返回一次 EOF,它将继续返回 EOF,即使有新数据可用,除非您使用上述方法之一用于清除 eof 标志。

一些不一致的实现可能会立即提供新数据。这种行为是有害的,可能会破坏符合规范的应用程序。

关于c - getc() 是在返回 EOF 后定义的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4753869/

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