我在C練習中使用getc();
,回顧程序後,我發現一些奇怪的東西。我認爲在命令行參數上給出的文件至少包含一個字節。 (它在連續兩次調用getc();
時沒有檢查EOF
,在一個空文件上嘗試它後仍能正常工作我的問題是:是getc();
對已耗盡的文件指針的行爲(EOF已達到並且未被重新綁定)未定義還是會一直繼續返回EOF?getc()在返回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;
}
對不起,但只是爲了清楚起見,這是C還是C++?它看起來像C,但我寧願檢查,而不僅僅是編輯。 – 2011-01-20 23:32:45
這是C,我認爲它也可以應用於C++,但我會刪除標籤以減少歧義。 – orlp