C++ change newline from CR+LF to LF

c++, linux, newline, windows

Solution

Yes, you have to open the file in "binary" mode to stop the newline translation.

How you do it depends on how you are opening the file.

Using `fopen`:

FILE* outfile = fopen( "filename", "wb" );

Using `ofstream`:

std::ofstream outfile( "filename", std::ios_base::binary | std::ios_base::out );

Problem

I am writing code that runs in Windows and outputs a text file that later becomes the input to a program in Linux. This program behaves incorrectly when given files that have newlines that are CR+LF rather than just LF. I know that I can use tools like dos2unix, but I'd like to skip the extra step. Is it possible to get a C++ program in Windows to use the Linux newline instead of the Windows one?

Original source