Fundamentals 5 min read

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.

Liangxu Linux
Liangxu Linux
Liangxu Linux
What’s the Real Difference Between \n and \r? A Deep Dive into Newline and Carriage Return

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

newlinecontrol characterscarriage returnOS differencestext encoding
Liangxu Linux
Written by

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.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.