feof
來自 cppreference.com
定義於標頭檔案 <stdio.h> |
||
int feof( FILE *stream ); |
||
檢查給定檔案流是否已到達末尾。
目錄 |
[編輯] 引數
stream | - | 要檢查的檔案流 |
[編輯] 返回值
如果流已到達末尾,則返回非零值,否則返回 0。
[編輯] 注意
此函式僅報告最近一次 I/O 操作報告的流狀態,它不檢查關聯的資料來源。例如,如果最近一次 I/O 是 fgetc,它返回檔案的最後一個位元組,則 feof
返回零。下一次 fgetc 將失敗並將流狀態更改為“檔案結束”。只有這樣,feof
才返回非零值。
在典型用法中,輸入流處理在任何錯誤發生時停止;然後使用 feof
和 ferror 來區分不同的錯誤條件。
[編輯] 示例
執行此程式碼
#include <stdio.h> #include <stdlib.h> int main(void) { const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL); int is_ok = EXIT_FAILURE; FILE* fp = fopen(fname, "w+"); if (!fp) { perror("File opening failed"); return is_ok; } fputs("Hello, world!\n", fp); rewind(fp); int c; // note: int, not char, required to handle EOF while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop putchar(c); if (ferror(fp)) puts("I/O error when reading"); else if (feof(fp)) { puts("End of file is reached successfully"); is_ok = EXIT_SUCCESS; } fclose(fp); remove(fname); return is_ok; }
可能的輸出
Hello, world! End of file is reached successfully