跳轉到內容

C 程式設計/stdio.h/feof

來自華夏公益教科書,開放的書籍,為開放的世界

feof 是一個 C 標準庫函式,在標頭檔案 stdio.h 中宣告。[1] 它的主要目的是區分流操作到達檔案末尾的情況和EOF(“檔案末尾”)錯誤程式碼作為通用錯誤指示器返回的情況,而實際上並沒有到達檔案末尾。

函式原型

[編輯 | 編輯原始碼]

該函式的宣告如下:

int feof(FILE *fp);

它接受一個引數:指向要檢查的流的FILE 結構的指標。

返回值

[編輯 | 編輯原始碼]

該函式的返回值是一個整數。非零值表示已到達檔案末尾;值為零表示尚未到達檔案末尾。

示例程式碼

[編輯 | 編輯原始碼]
 #include <stdio.h>
 
 int main()
 {
     FILE *fp = fopen("file.txt", "r");
     int c;
     c = getc(fp);
     while (c != EOF) {
         /* Echo the file to stdout */
         putchar(c);
         c = getc(fp);
     }
     if (feof(fp))
       puts("End of file was reached.");
     else if (ferror(fp))
       puts("There was an error reading from the stream.");
     else
       /*NOTREACHED*/
       puts("getc() failed in a non-conforming way.");
 
     fclose(fp);
     return 0;
 }

對該函式的一種常見誤用是嘗試使用feof“搶先”。但是,這不能正常工作,因為feof僅在讀取函式失敗後才為描述符設定。

參考文獻

[編輯 | 編輯原始碼]
  1. ISO/IEC 9899:1999 規範 (PDF). p. 305, § 7.19.10.2.
[編輯 | 編輯原始碼]
華夏公益教科書