繁体   English   中英

以二进制模式写入标准输出的最简单方法是什么?

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

我一直在试图找出将二进制数据从 C 程序写入标准输出的最佳方法。 它在 Linux 上运行良好,但在 Windows 上编译时遇到问题,因为“\\n”被转换为“\\r\\n”。

是否有一种标准方法可以避免换行转换,以某种二进制模式写入 stdout? 如果没有,让 Windows 停止这样做的最简单方法是什么?

我正在使用 GCC 和 MinGW,并使用fwrite写入stdout

您可以使用setmode(fileno(stdout), O_BINARY)

如果您想让它与 Linux 兼容,请将其包装在 ifdef 中。

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

你可以做这样的事情(这是一种跨平台):

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

或者您可以直接将write()read()系统调用与fileno(stdin)fileno(stdout) 这些系统调用在较低级别上运行并且不进行任何转换。 但是它们也没有您从FILE流中获得的缓冲。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM