Windows carriage return is \r\n
while it is \n
in Unix, is \r\n
treated as two characters?
These are two characters:
\r
is carriage return;\n
is line feed.
Two characters combined represent a new line on Windows. Whereas on Linux, \n
represents new line. It moves cursor to the start of new line on Linux. On Windows, the cursor will stay at the same column in the console but on the next line.
\r
on Linux has the same effect as on Windows: moves cursor to the start of the line. It is possible to print different information on the same line where \r
is used instead of \n
.
\n
is not required to be line feed (LF). The standard requires that '\n' be a single char
value that text mode i/o will translate to and from the platform's preferred sequence for beginning a new line. That said, all C implementations I know of choose to use LF for \n
. Then again, I don't have hands-on experience with any C compilers that target EBCDIC. –
Anthill Actually \r is 0x0D (^M) and \n is 0x0A (^J)
, but..... on windows:
\n will write 0x0D 0x0A
on unix:
\r will write 0x0D
\n will write 0x0A
stdout
as a binary stream rather than a text stream would result in \n
writing sole 0x0A
rather than 0x0D 0x0A
on Windows. See @FredFoo 's anwer. –
Seven Depends on the setting. \r\n
is two bytes wide (in ASCII, UTF-8, etc.), but I/O libraries such C's stdio
library and others, when operating in text mode, may translate between \n
and \r\n
quasi-transparently.
I.e., on a Windows platform, a C program reading a text-mode stream txt_in
with
while ((c = getc(txt_in)) != EOF)
printf("%02x\n", c);
will not report the ASCII code for \r
. Conversely, putc('\n', txt_out)
will actually write \r\n
to the text-mode stream txt_out
.
Windows doesn't distinguish between \r\n
and any other two characters. However, there is one situation where it is treated as one character: if you use the C runtime and open a file as text, \r\n
in the file will be read as \n
, and \n
will be written to the file as \r\n
.
Yes, it's two characters: carriage return '\r' followed by linefeed '\n'.
I conducted some tests (nothing fancy) with Notepad++ and Sublime Text 2 on Windows, and it turns out that \r
and \n
are indeed 2 distinct characters, but...
Different text editors might insert or they might not insert \r
when Return key is pressed.
Try the following in your text editor:
1
2
3
4
5
Then press Ctrl+F, enable regular expressions and search for \r
. Depending on your text editor and its settings, you might 'hit' or 'not hit' a character at the end of each line. If the above text is copy-pasted from another editor, behavior might also differ...
Some text editors allow for customizations in their settings, where you can specify if you prefer \r\n
or unix-style \n
to be inserted when you press Return. On top of that, they might allow you to choose to enforce a consistent style by stripping or inserting the \r
character before saving a file.
© 2022 - 2024 — McMap. All rights reserved.