gpt4 book ai didi

c++ - fprintf 和 WriteConsole 的输出以相反的顺序发生

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:23 26 4
gpt4 key购买 nike

我在 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 不这样做?

最佳答案

这可能与添加到输出的一些缓冲 stdio.h 有关。尝试添加一个

fflush(fout);

fprintf 之后。或者你可以尝试一个

setbuf(fout, null);

为您的输出流禁用缓冲。

至于“奖励”(printf 正常工作):Afaik stout 通常设置为在每个换行后自动刷新。

关于c++ - fprintf 和 WriteConsole 的输出以相反的顺序发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25776890/

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