C 庫 - feof() 函式



C 庫函式 int feof(FILE *stream) 用於測試給定流的檔案結束指示符。此函式是標準輸入/輸出庫 (stdio.h) 的一部分,對於以受控方式管理檔案讀取操作非常重要。

語法

以下是 C 庫函式 feof() 的語法:

int feof(FILE *stream);

引數

此函式僅接受一個引數:

  • FILE *stream: 指向 FILE 物件的指標,用於標識要檢查的流。

返回值

如果與流關聯的檔案結束指示符已設定,則 feof 函式返回非零值。否則,它返回零。

示例 1:直到 EOF 的基本檔案讀取

此程式從 example.txt 檔案讀取字元並列印它們,直到 feof 指示檔案結尾。

以下是 C 庫 feof() 函式的示例。

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   while (!feof(file)) {
       char c = fgetc(file);
       if (feof(file)) break;
       putchar(c);
   }

   fclose(file);
   return 0;
}

輸出

以上程式碼將 example.txt 檔案的內容列印到控制檯作為結果。

Welcome to tutorials point

示例 2:使用 fgets 讀取行直到 EOF

此程式使用 fgets 從 example3.txt 讀取行並列印它們,直到 feof 確認已到達檔案結尾。

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   char buffer[256];
   while (fgets(buffer, sizeof(buffer), file) != NULL) {
       printf("%s", buffer);
   }

   if (feof(file)) {
       printf("End of file reached.\n");
   }

   fclose(file);
   return 0;
}

輸出

執行上述程式碼後,將逐行列印 example3.txt 的內容,然後是訊息:

End of file reached.
廣告
© . All rights reserved.