Portable end of line (newline)

Ali picture Ali · Dec 31, 2011 · Viewed 9.5k times · Source

It's been an unpleasant surprise that '\n' is replaced with "\r\n" on Windows, I did not know that. (I am guessing it is also replaced on Mac...)

Is there an easy way to ensure that Linux, Mac and Windows users can easily exchange text files?

By easy way I mean: without writing the file in binary mode or testing and replacing the end-of-line chars myself (or with some third party program/code). This issue effects my C++ program doing the text file I/O.

Answer

Konrad Rudolph picture Konrad Rudolph · Dec 31, 2011

The issue isn’t with endl at all, it’s that text streams reformat line breaks depending on the system’s standard.

If you don’t want that, simply don’t use text streams – use binary streams. That is, open your files with the ios::binary flag.

That said, if the only issue is that users can exchange files, I wouldn’t bother with the output mode at all, I’d rather make sure that your program can read different formats without choking. That is, it should accept different line endings.

This is by the way what any decent text editor does (but then again, the default notepad.exe on Windows is not a decent text editor, and won’t correctly handle Unix line breaks).