简体   繁体   English

linux如何检测文本文件的EOF?

[英]How does linux detect the EOF of a text file?

I was wondering how Linux detects the end of a text file.我想知道 Linux 如何检测文本文件的结尾。 Do all text files end in a NULL byte, and Linux takes advantage of this?所有文本文件是否都以 NULL 字节结尾,而 Linux 是否利用了这一点?

Modern operating systems, such as Linux, do not use the file contents to detect the end of file, they store the file length in the file system and keep track of the file position to determine if more contents is available to read.现代操作系统,例如 Linux,不使用文件内容来检测文件的结尾,它们将文件长度存储在文件系统中并跟踪文件 position 以确定是否有更多内容可供读取。

In fact text files are not supposed to contain null bytes at all.事实上,文本文件根本不应该包含 null 字节。 They usually end with an end of line marker ( \n on linux an OS/X, CR / LF on legacy systems).它们通常以行尾标记结束( linux 上的\n和 OS/X,旧系统上的CR / LF )。 One notable exception to this rule is the empty file.此规则的一个显着例外是空文件。

When reading from a device such as the terminal window, the OS relies on the device driver to provide information about the end of file, which in the case of the terminal can be signalled by the user by entering a system specific key combination such as Ctrl D on unix systems and Ctrl Z Enter on Microsoft operating systems.从诸如终端 window 之类的设备读取时,操作系统依靠设备驱动程序提供有关文件结尾的信息,在终端的情况下,用户可以通过输入系统特定的组合键(例如Ctrl )来发出信号unix 系统上的D和 Microsoft 操作系统上的Ctrl Z Enter

From program point of view, EOF can detect using below API从程序来看, EOF可以使用下面的API检测

  1. read() return 0. read()返回 0。
  2. getchar() returns -1. getchar()返回 -1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM