Why should text files end with a newline?

后端 未结 18 1215
栀梦
栀梦 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: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'.

提交回复
热议问题