What is the simplest way to write to stdout in binary mode?

≯℡__Kan透↙ 提交于 2019-12-17 07:47:06

问题


I've been trying to figure out the best way to write binary data to stdout from a C program. It works fine on Linux, but I'm having issues when I compile on Windows because "\n" gets converted to "\r\n".

Is there a standard way to write to stdout in some sort of binary mode which avoids newline conversion? If not, what is the simplest way to get Windows to stop doing this?

I'm using GCC and MinGW.


回答1:


You can use setmode(fileno(stdout), O_BINARY)

Wrap it in an ifdef if you want to keep it compatible with Linux.

See also: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmode?view=vs-2017




回答2:


You can do something like that (which is sort of cross platform):

FILE *const in = fdopen(dup(fileno(stdin)), "rb");
FILE *const out = fdopen(dup(fileno(stdout)), "wb");
/* ... */
fclose(in);
fclose(out);

Or you can use write() and read() system calls directly with fileno(stdin) and fileno(stdout). Those system calls operate on lower level and don't do any conversions. But they also don't have buffering that you get from FILE streams.



来源:https://stackoverflow.com/questions/16888339/what-is-the-simplest-way-to-write-to-stdout-in-binary-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!