Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ change newline from CR+LF to LF

Tags:

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?

like image 293
thornate Avatar asked Oct 08 '09 06:10

thornate


People also ask

Is \n LF or CRLF?

Description. The term CRLF refers to Carriage Return (ASCII 13, \r ) Line Feed (ASCII 10, \n ). They're used to note the termination of a line, however, dealt with differently in today's popular Operating Systems.

What is CRLF character?

The CRLF abbreviation refers to Carriage Return and Line Feed. CR and LF are special characters (ASCII 13 and 10 respectively, also referred to as \r\n) that are used to signify the End of Line (EOL).

Is Windows LF or CRLF?

Whereas Windows follows the original convention of a carriage return plus a line feed ( CRLF ) for line endings, operating systems like Linux and Mac use only the line feed ( LF ) character.


1 Answers

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 ); 
like image 175
CB Bailey Avatar answered Sep 30 '22 20:09

CB Bailey