在windows命令行重定向下的c ++换行符 [英] c++ newline character under windows command line redirection

查看:461
本文介绍了在windows命令行重定向下的c ++换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现Windows命令行重定向会自动将'\\\
'替换为'\r\\\
'。有没有办法避免这种情况?因为在stdout或stderr重定向后,如果你写'\r\\\
'到控制台,你将得到'\r\r\\\
'而不是'\r\\\
'。

I found that Windows command line redirection will replace '\n' with '\r\n' automatically. Is there any method to avoid this situation? Because after stdout or stderr redirection, you will got '\r\r\n' instead of '\r\n' if you write '\r\n' to the console.

非常感谢!

您可以尝试一个简单的程序:

you can just try a simple program:

fprintf(stdout,"Hello, world!\r\n");

然后使用重定向运行:

demo 1>demo.log

,您会发现'\r\\\
'由'\r\r\\\
'表示。

By using any HEX editor, you will find that '\r\n' is represented by '\r\r\n'.

UPDATE:

@ steve-jessop我已经通过使用 setmode 解决了这个问题,这将强制 stdout 使用 O_BINARY 方式。因此,该流不会将 \\\
翻译为 \r\\\

@steve-jessop I have solved this problem by using setmode, which will force stdout using O_BINARY mode. So the stream won't translate \n into \r\n.

感谢太多了!

推荐答案

避免它的方法是不写Hello,world!\r\\\
fprintf(stdout,Hello,world!\\\
);
std :: cout< 你好,世界! <<

The way to avoid it is to not write "Hello, world!\r\n". Either fprintf(stdout,"Hello, world!\n"); or std::cout << "Hello, world!" << std::endl; is sufficient.

这不是特殊的命令行重定向或 stdout

This isn't particular to command-line redirection or stdout, the same would be true with any file descriptor open in character mode (as opposed to binary mode).

这篇关于在windows命令行重定向下的c ++换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆