Why should text files end with a newline?

后端 未结 18 1717
栀梦
栀梦 2020-11-21 22:56

I assume everyone here is familiar with the adage that all text files should end with a newline. I\'ve known of this \"rule\" for years but I\'ve always wondered — why?

18条回答
  •  清歌不尽
    2020-11-21 23:31

    In addition to the above practical reasons, it wouldn't surprise me if the originators of Unix (Thompson, Ritchie, et al.) or their Multics predecessors realized that there is a theoretical reason to use line terminators rather than line separators: With line terminators, you can encode all possible files of lines. With line separators, there's no difference between a file of zero lines and a file containing a single empty line; both of them are encoded as a file containing zero characters.

    So, the reasons are:

    1. Because that's the way POSIX defines it.
    2. Because some tools expect it or "misbehave" without it. For example, wc -l will not count a final "line" if it doesn't end with a newline.
    3. Because it's simple and convenient. On Unix, cat just works and it works without complication. It just copies the bytes of each file, without any need for interpretation. I don't think there's a DOS equivalent to cat. Using copy a+b c will end up merging the last line of file a with the first line of file b.
    4. Because a file (or stream) of zero lines can be distinguished from a file of one empty line.

提交回复
热议问题