【发布时间】:2014-09-10 23:51:29
【问题描述】:
我在 Windows 中看到控制台 I/O 的奇怪行为。当我使用CONOUT$ 作为路径打开FILE * 时,它应该打开控制台的stdout。如果我将该指针用于fprintf,然后是WriteConsole,您会认为消息会按各自的顺序出现,但实际上它们是相反的。
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <io.h>
int main(int argc, char *argv[]) {
FILE *fout = fopen("CONOUT$", "w");
fprintf(fout, "Hello world!\n");
LPSTR goodbye = "Goodbye, cruel world!\n";
DWORD length = strlen(goodbye);
DWORD written;
WriteConsole(_get_osfhandle(_fileno(fout)), goodbye, length, &written, NULL);
return 0;
}
还有输出:
Goodbye, cruel world!
Hello world!
这是为什么?我的猜测与 Win32 I/O 函数和 stdio 同步(或者更确切地说,不同步)的方式有关。我知道 C++ iostream 需要特别注意与 stdio 同步,所以也许 Win32 不这样做?
【问题讨论】:
-
我刚刚意识到的一个好处是:如果您将
fprintf更改为只调用printf,则排序将按您的预期工作。这是为什么呢? -
我想知道这是否是
stdio.h的缓冲问题,但我不确定为什么新的FILE句柄和stdout会有所不同。我得再读一遍标准。 -
@andlabs:“打开时,当且仅当可以确定不引用交互式设备时,流才被完全缓冲。流的错误和文件结束指示符被清除。”这就是标准所说的。但是Windows stdio库是否符合,我不知道。
-
通过打开 CONOUT$,您绕过了对标准输出流执行的正常检查,是否需要自动刷新。