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僅在讀取函式失敗後才為描述符設定。
- ↑ ISO/IEC 9899:1999 規範 (PDF). p. 305, § 7.19.10.2.