简体   繁体   中英

C++ change newline from CR+LF to LF

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?

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

A much cleaner solution is to use the ASCII escape sequence for the LF character (decimal 10): '\\012' or '\\x0A' represents an explicit single line feed regardless of platform.

This method also avoids string length surprises, as '\\n' can expand to two characters. But so can multibyte unicode characters, in UTF8, when written directly into a string literal in the source code.

Note also that '\\r' is the platform-independent code for a single carriage return (decimal 13). The '\\f' character is not the line feed, but rather the form feed (decimal 12), which is not a newline on any platform I am aware of. C does not offer a single-character backslash escape for the line feed, thus the need for the longer octal or hexadecimal escapes.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM