简体   繁体   中英

How does linux detect the EOF of a text file?

I was wondering how Linux detects the end of a text file. Do all text files end in a NULL byte, and Linux takes advantage of this?

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.

In fact text files are not supposed to contain null bytes at all. They usually end with an end of line marker ( \n on linux an OS/X, CR / LF on legacy systems). 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.

From program point of view, EOF can detect using below API

  1. read() return 0.
  2. getchar() returns -1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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