0
0

【POSIX】何故ファイルの末尾に改行が必要なのか

Posted at

「ファイルの末尾に改行を入れてね」と言われた経験はありませんか?
何故ファイルの末尾に改行を入れる必要があるのでしょうか・・・

なんで末尾に改行を入れないといけないのか

POSIXに準拠した仕様だから
「基本的に標準仕様には従おうね」ということだそうです。

これでは納得できない人もいると思うのでPOSIXについて少し掘り下げていきます。

POSIXとは何か

Portable Operating System Interfaceを略したもので、オペレーティングシステムの標準的なインタフェースや環境を定義するIEEEの規格になります。

詳しくは下記のWEBサイトを見てください

結局なんで改行が必要なの?

改行が必要な理由については、POSIXの 3. Definitions に書かれています。
特にテキストに関連する記述を抜き出しました。

3.46 Blank Line
A line consisting solely of zero or more characters terminated by a ; see also 3.120 Empty Line .

3.120 Empty Line
A line consisting of only a ; see also 3.46 Blank Line .

3.172 Incomplete Line
A sequence of one or more non- characters at the end of the file.

3.185 Line
A sequence of zero or more non- characters plus a terminating character.

3.387 Text File
A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the character. Although POSIX.1-2024 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.

これらをまとめると、POSIXではテキストについて

  1. テキストファイルは0行以上の行にまとめられた文字を含むファイル
  2. 行は改行コードのみ、もしくは行の最後に改行コードがある文字列

と定められていると解釈できます。

まとめ

POSIXの形式では行の末尾には改行コードが必要だと定められているため、ファイルの末尾に改行が無いと最後の行が不完全な行だと認識されます。
そのため、最後の行だけ認識されない可能性があるということですね。

全ての行を「行である」と認識させるためにファイルの末尾に改行が必要だということです。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0