Question

Now line separator is system dependent but while in a c program i use '\n' for line separator , it works fine whether i run it in windows or linux . why ??

In java we have to use %n as it is system dependent then how come we use '\n' in c for new line irrespective of os in which we run it ?

Was it helpful?

Solution

Here's what C99 standard has to say about it:

5.2.2 Character display semantics
[...]
2. Alphabetic escape sequences representing nongraphic characters in the execution
character set are intended to produce actions on display devices as follows:
[...]
\n (new line) Moves the active position to the initial position of the next line.

This means that if you print "\n", it has to be changed to "\r\n" on windows in order to fulfill this requirement. But this is only defined this way for display devices, not for files. There is no specification on how this (or any other whitespace) character should be represented in text-file, however:

5.2.2 Character display semantics
[...]
3. Each of these escape sequences shall produce a unique implementation-defined value
which can be stored in a single char object. The external representations in a text file
need not be identical to the internal representations, and are outside the scope of this
International Standard.

So the direct answer to your question is - it works as you would expect because the C standard does not say anything about binary representation of \n character when it's printed to the display device or stored in text-file. It does, however, precisely specify how it should behave when printed - it should move to the beginning of next line.

OTHER TIPS

In C programs, you specify when you open the file whether it is text or binary -- when you open a file with fopen, you specify a mode string, which includes b if this is a binary file. When reading from and writing to text-mode files, the C library will automatically translate between '\n' characters and the system line separator.

In java, there is no analogous "text mode" that automatically translates for you, so to deal with line separators, you need to do it explicitly in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top