What’s the Real Difference Between \n and \r? A Deep Dive into Newline and Carriage Return
This article explains the historical origins, technical meanings, and platform-specific behaviors of the \n (newline) and \r (carriage return) control characters, showing how they affect file formatting across Windows, Unix, and macOS and how to convert between them.
About \n and \r
In ASCII, \n and \r are non‑printable control characters: \n is the newline (line feed, LF, ASCII 10) that moves the cursor down one line, while \r is the carriage return (CR, ASCII 13) that returns the cursor to the beginning of the line.
Historical Origin
Early teletypes (e.g., Teletype Model 33) could print only ten characters per second. To signal the end of a line without losing incoming characters, engineers added two separate characters: a carriage return to move the print head to the left margin and a line feed to advance the paper.
Typical Usage in Code
printf('hello world!
');Most programming languages use the combined sequence "\r\n" to represent the Enter key.
OS newline conventions
MS‑DOS/Windows: CR+LF ("\r\n")
Unix/Linux: LF only ("\n")
Classic Mac OS: CR only ("\r")
Therefore, when writing cross‑platform text files, the line‑ending is often referred to as a “carriage‑return‑line‑feed” sequence.
Impact of Mismatched Line Endings
Opening a Unix‑style file on Windows may display the whole content as a single line, while a Windows file opened on Unix may show a stray "^M" character at the end of each line.
Conversion Tools
On Linux, the unix2dos command converts LF endings to CR+LF, and dos2unix does the reverse. FTP clients in ASCII mode may also rewrite line endings automatically; using binary mode preserves the original bytes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
