tags:

views:

547

answers:

3

Unix has \n, Mac was \r but is now \n and DOS/Win32 is \r\n. When creating a text file with C, how to ensure whichever end of line character(s) is appropriate to the OS gets used?

+10  A: 
fprintf(your_file, "\n");

This will be converted to an appropriate EOL by the stdio library on your operating system provided that you opened the file in text mode. In binary mode no conversion takes place.

hlovdal
IF the file is opened in text mode
1800 INFORMATION
Yes, of course. I should have included that from the start. Updated now.
hlovdal
The asker talked explicitly about text files.
Joey
Ah, didn't know that! +1
rascher
+11  A: 

From Wikipedia:

When writing a file in text mode, '\n' is transparently translated to the native newline sequence used by the system, which may be longer than one character. (Note that a C implementation is allowed not to store newline characters in files. For example, the lines of a text file could be stored as rows of a SQL table or as fixed-length records.) When reading in text mode, the native newline sequence is translated back to '\n'. In binary mode, the second mode of I/O supported by the C library, no translation is performed, and the internal representation of any escape sequence is output directly.

Dan Olson
+7  A: 

When you open a file in text mode (pass "w" to fopen instead of "wb") any newline characters written to the file will automatically be converted to the appropriate newline sequence for the system. Newline sequences will be translated back to newline characters when you read the file.

This is why it's important to distinguish between text and binary mode; if you're writing in binary mode, C will not tamper with the bytes you write to a file.

Jay Conrod
+1 for mentioning the distinction between text and binary files (and for beating me to it!)
Harper Shelby