Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ newline character under windows command line redirection

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.

Thanks a lot!

you can just try a simple program:

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

then you run it with redirection:

demo 1>demo.log

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

UPDATE:

@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.

Thanks a lot!

like image 230
user594561 Avatar asked Jan 26 '26 06:01

user594561


1 Answers

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.

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).

like image 140
Steve Jessop Avatar answered Jan 28 '26 01:01

Steve Jessop