by Gene Michael Stover
created Thursday, 2026 January 8
updated Thursday, 2026 January 8
original at cybertiggyr.com/m256k07.html
I prefer to end a text file with a newline[1], but I don't remember why I prefer it, so I wonder if it's a best practice.
So here, to settle it for myself now & forever (for now)[2], here's the conclusion & the rationale.
When I mention this to friends, they sometimes suggest
using <br /> to break lines. Any answer
suggestion <br /> comes from someone who did
not understand the question.
Here's an attempt to avoid the confusion by stating the question in other terms...
Let's say that File A contains the octets for “hello,
world”. If I write those octets in hex, that's
6865 6c6c 6f2c 2077 6f72 6c64.
Let's say that File B contains the same octets with a unix-style
end-of-line at the end. In hex, the octets for File B are
6865 6c6c 6f2c 2077 6f72 6c64 0a.
Which is preferred: File A or File B?
(We could also have File C which has the octets from File A followed by
an MS-DOS-style end-of-line, 0d0a. The entire file content
would be
6865 6c6c 6f2c 2077 6f72 6c64 0d0a. I'll assume
that, on a system that uses 0d0a as the end-of-line
sequence, File C is equivalent to File B on a system that uses
just 0a as the end-of-line sequence.)
Terminate the final line with a newline. In other words, File B is preferred.
The POSIX standard defines a line of text as a bunch of characters followed by an end-of-line. So to conform to the POSIX standard, even the final line should end with an end-of-line.
That said, you should write text-consuming programs to work even if the final line ends with the end-of-file.
A decent discussions is “Why should text files end with a newline?”. It's Stackoverflow #729692.
Note 1. An HTML file is a kind of text file.
Note 2. “now & forever (for now)” is humor.