Why Do Windows and Unix Use Different Line Endings? Understanding \n vs \r
The article explains the historical origins of the carriage‑return (\r) and line‑feed (\n) control characters, their ASCII codes, how various operating systems (Windows, Unix, macOS) represent line endings, the practical impact on file compatibility, and tools for converting between formats.
What are \n and \r?
In the ASCII table, \n is the line‑feed (LF) character with code 10, which moves the cursor down one line. \r is the carriage‑return (CR) character with code 13, which returns the cursor to the beginning of the current line.
Historical background
Early teleprinters such as the Teletype Model 33 printed characters at about 10 cps. When a line finished, the machine needed 0.2 seconds to return the carriage to the left margin; during that time incoming characters could be lost. To avoid loss, the device used two control characters: CR to move the carriage home and LF to advance the paper.
How modern systems use them
When computers adopted the teleprinter conventions, some designers argued that a single character would suffice, leading to differing line‑ending conventions:
MS‑DOS/Windows: CR + LF (\r\n)
Unix/Linux: LF only (\n)
Classic macOS (pre‑OS X): CR only (\r)
Because of these differences, a file created on one platform may appear as a single long line on another, or show stray “^M” characters.
Practical impact
Opening a Unix‑style file in Windows Notepad shows all text on one line; opening a Windows‑style file on Unix may display a visible carriage‑return symbol. Some editors accept only \r\n, while others accept either character.
Conversion tools
On Linux, the unix2dos command converts LF line endings to CR + LF, and dos2unix does the reverse. When transferring files via FTP, using ASCII mode may automatically translate line endings, so binary mode should be chosen to preserve the original bytes.
Example code
Typical C code that prints a line with Windows‑style termination:
printf('hello world!
');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.
