fprintf和WriteConsole的输出顺序相反
Output of fprintf and WriteConsole happen in reverse order
我在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);
在CCD_ 10。或者你可以试试
setbuf(fout, null);
禁用输出流的缓冲。
至于"奖金"(printf
工作正常):Afaik stout
通常以在每一行换行后自动刷新的方式设置。
这几乎肯定与stdio
缓冲有关,尽管理论上fout
不应该完全缓冲。
C11§7.21.5.3/8:"当打开时,当且仅当可以确定流不是指交互式设备时,流才被完全缓冲。流的错误和文件结尾指示符被清除。"因此,Windows stdio实现可能不可能确定CONOUT$
是交互式设备,但标准的措辞似乎是,如果有疑问,流不应该被完全缓冲地打开。它可能是开放的行缓冲的,但您在fprintf
中输出了一个n
,所以在这种情况下,您应该很好,事实上,使用printf
或多或少可以证明这一点。
您可以尝试使用setvbuf
关闭fout
上的缓冲,看看这是否有帮助。
这肯定是stdio的缓冲。我在MSVC2012和mingw-w64实现中都收到了相同的输出。
我决定从stdio层切换到POSIX层,结果是:
Hello world!
Goodbye, cruel world!
您的代码,略有修改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
int fout = _open("CONOUT$", _O_WRONLY);
char *hello = "Hello world!n";
_write(fout, hello, strlen (hello));
LPSTR goodbye = "Goodbye, cruel world!n";
DWORD length = strlen(goodbye);
DWORD written;
WriteConsole(_get_osfhandle(fout), goodbye, length, &written, NULL);
_close(fout);
return 0;
}
相关文章:
- 如何在 C++ 中将从文本文件中读取的元素推送和弹出到数组中,并按 Revserse 顺序输出堆栈?
- 堆排序,我无法弄清楚我的代码出了什么问题,输出顺序不正确
- C++ 以相反的顺序输出文本文件
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- `sTD :: sample()的输出序列是否遵循输入序列的顺序
- cout 和 cerr 的控制台输出顺序错误
- C 的输出顺序错误
- 以特定顺序输出地图
- 以正确的顺序输出队列
- 输出未按正确的顺序打印
- 更改声明顺序时输出不正确
- VC++编译器输出顺序
- 为什么 bool 显示正确的位顺序,而直接输出移位运算结果却不显示?
- C++输出顺序
- 顺序我正在检查输出错误的字符串
- OpenCL计算与顺序算法的输出不匹配
- 数字的基本表示-输出顺序相反
- 按相反顺序输出数组的元素
- 如何创建矢量并按相反顺序输出
- c++指针声明顺序输出分段错误或总线错误