3

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!

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

the thing is that std::endl is not just a new line, it also flushes and has impact on performance depending where added
6

'\n' is the platform-independent newline representation. It's expanded by the compiler to whatever is the actual newline representation for the platform you're compiling for -- '\r\n' for Windows, and '\n' for *nix and friends, including MacOS.

So this is why you see '\r\r\n' in hex editor -- '\n' from '\r\n' that you wrote in source was expanded to '\r\r\n'.

3 Comments

It's not expanded by the compiler, it's expanded by the stream when it's written. strlen("\n") is always 1.
@Steve Thanks for the correction! I had somehow gotten it into my head that it was a compile-time thing, not runtime. One quick experiment later I see that I was wrong.
You mean MacOS X. It is '\r' for classic MacOS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.