Rob Kam
Rob Kam

Reputation: 10268

In C how to write whichever end of line character is appropriate to the OS?

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?

Upvotes: 7

Views: 3593

Answers (3)

hlovdal
hlovdal

Reputation: 28180

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.

Upvotes: 12

Jay Conrod
Jay Conrod

Reputation: 29681

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.

Upvotes: 9

Dan Olson
Dan Olson

Reputation: 23367

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.

Upvotes: 12

Related Questions