【发布时间】:2011-01-20 23:28:33
【问题描述】:
我在 C 练习中使用了getc();,在回顾程序后,我发现了一些奇怪的东西。我假设命令行参数中给出的文件至少包含一个字节。 (它连续两次调用getc(); 而不检查EOF。在空文件上尝试后它仍然工作顺利。我的问题是:是getc(); 在文件指针上的行为已经用尽(已达到 EOF 且未倒带)未定义还是会一直继续返回 EOF?
我想我可以将此问题扩展到 C STL 中的所有 I/O 函数,请在您的回答中也澄清这一点。
这是程序的代码。该程序应该从所有 cmets 中剥离 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;
}
【问题讨论】:
-
抱歉,为了清楚起见,这是 C 还是 C++?它看起来像 C,但我宁愿检查而不仅仅是编辑。
-
它是 C,我认为它也适用于 C++,但我将删除标记以减少歧义。