C++ change newline from CR+LF to LF C++ change newline from CR+LF to LF linux linux

C++ change newline from CR+LF to LF


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


OK, so this is probably not what you want to hear, but here's my $0.02 based on my experience with this:

If you need to pass data between different platforms, in the long run you're probably better off using a format that doesn't care what line breaks look like. If it's text files, users will sometimes mess with them. If by messing the line endings up they cause your application to fail, this is going to be a support intensive application.

Been there, done that, switched to XML. Made the support guys a lot happier.