Why should text files end with a newline?

后端 未结 18 1129
栀梦
栀梦 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条回答
  • It's very late here but I just faced one bug in file processing and that came because the files were not ending with empty newline. We were processing text files with sed and sed was omitting the last line from output which was causing invalid json structure and sending rest of the process to fail state.

    All we were doing was:

    There is one sample file say: foo.txt with some json content inside it.

    [{
        someProp: value
    },
    {
        someProp: value
    }] <-- No newline here
    

    The file was created in widows machine and window scripts were processing that file using PowerShell commands. All good.

    When we processed same file using sed command sed 's|value|newValue|g' foo.txt > foo.txt.tmp

    The newly generated file was

    [{
        someProp: value
    },
    {
        someProp: value
    

    and boom, it failed the rest of the processes because of the invalid JSON.

    So it's always a good practice to end your file with empty new line.

    0 讨论(0)
  • 2020-11-21 23:35

    Because that’s how the POSIX standard defines a line:

    3.206 Line
    A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

    Therefore, lines not ending in a newline character aren't considered actual lines. That's why some programs have problems processing the last line of a file if it isn't newline terminated.

    There's at least one hard advantage to this guideline when working on a terminal emulator: All Unix tools expect this convention and work with it. For instance, when concatenating files with cat, a file terminated by newline will have a different effect than one without:

    $ more a.txt
    foo
    $ more b.txt
    bar$ more c.txt
    baz
    $ cat {a,b,c}.txt
    foo
    barbaz

    And, as the previous example also demonstrates, when displaying the file on the command line (e.g. via more), a newline-terminated file results in a correct display. An improperly terminated file might be garbled (second line).

    For consistency, it’s very helpful to follow this rule – doing otherwise will incur extra work when dealing with the default Unix tools.


    Think about it differently: If lines aren’t terminated by newline, making commands such as cat useful is much harder: how do you make a command to concatenate files such that

    1. it puts each file’s start on a new line, which is what you want 95% of the time; but
    2. it allows merging the last and first line of two files, as in the example above between b.txt and c.txt?

    Of course this is solvable but you need to make the usage of cat more complex (by adding positional command line arguments, e.g. cat a.txt --no-newline b.txt c.txt), and now the command rather than each individual file controls how it is pasted together with other files. This is almost certainly not convenient.

    … Or you need to introduce a special sentinel character to mark a line that is supposed to be continued rather than terminated. Well, now you’re stuck with the same situation as on POSIX, except inverted (line continuation rather than line termination character).


    Now, on non POSIX compliant systems (nowadays that’s mostly Windows), the point is moot: files don’t generally end with a newline, and the (informal) definition of a line might for instance be “text that is separated by newlines” (note the emphasis). This is entirely valid. However, for structured data (e.g. programming code) it makes parsing minimally more complicated: it generally means that parsers have to be rewritten. If a parser was originally written with the POSIX definition in mind, then it might be easier to modify the token stream rather than the parser — in other words, add an “artificial newline” token to the end of the input.

    0 讨论(0)
  • 2020-11-21 23:35

    Why should (text) files end with a newline?

    As well expressed by many, because:

    1. Many programs do not behave well, or fail without it.

    2. Even programs that well handle a file lack an ending '\n', the tool's functionality may not meet the user's expectations - which can be unclear in this corner case.

    3. Programs rarely disallow final '\n' (I do not know of any).


    Yet this begs the next question:

    What should code do about text files without a newline?

    1. Most important - Do not write code that assumes a text file ends with a newline. Assuming a file conforms to a format leads to data corruption, hacker attacks and crashes. Example:

      // Bad code
      while (fgets(buf, sizeof buf, instream)) {
        // What happens if there is no \n, buf[] is truncated leading to who knows what
        buf[strlen(buf) - 1] = '\0';  // attempt to rid trailing \n
        ...
      }
      
    2. If the final trailing '\n' is needed, alert the user to its absence and the action taken. IOWs, validate the file's format. Note: This may include a limit to the maximum line length, character encoding, etc.

    3. Define clearly, document, the code's handling of a missing final '\n'.

    4. Do not, as possible, generate a file the lacks the ending '\n'.

    0 讨论(0)
  • 2020-11-21 23:35

    IMHO, it's a matter of personal style and opinion.

    In olden days, I didn't put that newline. A character saved means more speed through that 14.4K modem.

    Later, I put that newline so that it's easier to select the final line using shift+downarrow.

    0 讨论(0)
  • 2020-11-21 23:38

    Presumably simply that some parsing code expected it to be there.

    I'm not sure I would consider it a "rule", and it certainly isn't something I adhere to religiously. Most sensible code will know how to parse text (including encodings) line-by-line (any choice of line endings), with-or-without a newline on the last line.

    Indeed - if you end with a new line: is there (in theory) an empty final line between the EOL and the EOF? One to ponder...

    0 讨论(0)
  • 2020-11-21 23:39

    It may be related to the difference between:

    • text file (each line is supposed to end in an end-of-line)
    • binary file (there are no true "lines" to speak of, and the length of the file must be preserved)

    If each line does end in an end-of-line, this avoids, for instance, that concatenating two text files would make the last line of the first run into the first line of the second.

    Plus, an editor can check at load whether the file ends in an end-of-line, saves it in its local option 'eol', and uses that when writing the file.

    A few years back (2005), many editors (ZDE, Eclipse, Scite, ...) did "forget" that final EOL, which was not very appreciated.
    Not only that, but they interpreted that final EOL incorrectly, as 'start a new line', and actually start to display another line as if it already existed.
    This was very visible with a 'proper' text file with a well-behaved text editor like vim, compared to opening it in one of the above editors. It displayed an extra line below the real last line of the file. You see something like this:

    1 first line
    2 middle line
    3 last line
    4
    
    0 讨论(0)
提交回复
热议问题