(C/C++)视窗中的EOF7

(C/C++) EOF in windows7

本文关键字:EOF7 C++      更新时间:2023-10-16
#include <cstdio>
void fcopy(FILE* from, FILE* to);
int main()
{
    fcopy(stdin, stdout);
    return 0;
}
void fcopy(FILE* from, FILE* to)
{
    int c;
    while ((c = getc(from)) != EOF) {
        putc(c, to);
    }
}

当我运行这个程序时,^Z (Ctrl+z( 会发生一些意外的行为,我会用它来指示 EOF。

我输入的"hello"执行"fcopy"中的while循环以打印相同的内容。

"^Z" 结束程序。

但是如果我输入"blahblah

^Zasdfasdf",而我希望程序打印"blahblah"并终止,它会用一个小箭头打印"blahblah→"并等待我的输入。无论我在这里写下什么,都会被完全一样地复制下来;它似乎重新执行循环,同时切断了在"^Z"之后写入的任何内容。

in: hello
out: hello
in: hello^Z
out/in: hello→?? // "??" is my input
out: ??
in: ^Z
termination

谁能澄清为什么该程序以这种方式工作?提前感谢您的任何帮助。

这是因为 Windows 终端程序(读取键盘输入并将其传递给程序(正在像这样处理 Ctrl+Z。它只意味着在行首按下时"输入的信号结束"。

请注意,C 中的EOF并不代表实际("物理"(字符,它是带外信号,指示"没有要读取的字符,因为文件已结束"。

一般来说,我希望你应该等待^Z而不是EOF。 ^Z 是 0x1A ASCII 字符 (http://en.wikipedia.org/wiki/Substitute_character(。另外,您绝对还应该检查EOF,因为文件可以在没有^Z的情况下结束

似乎出于某种原因,控制台应用程序在行为空时将 ^Z 解释为 EOF(我不确定为什么 - 这可能是合法行为,也可能只是 https://connect.microsoft.com/VisualStudio/feedback/details/798951/c-getc-breaks-when-encountering-character-26-or-1a-hex-ascii-sub 中建议的错误(

但是以下代码可以修复它:

#include <cstdio>
#define CTRL_Z_SUB 0x1A // CTRL_Z substitue ASCII key
void fcopy(FILE* from, FILE* to);
int main()
{
    fcopy(stdin, stdout);
    return 0;
}
void fcopy(FILE* from, FILE* to)
{
    int c = getc(from);
    while (c != EOF && c != CTRL_Z_SUB) {
        putc(c, to);
        c = getc(from);
    }
}