C 庫 - fclose() 函式



C 庫 fclose() 函式用於關閉開啟的檔案流。它關閉流,並重新整理所有緩衝區。

語法

以下為 C 庫中 fclose() 函式的語法 −

int fclose(FILE *stream);

引數

此函式只接受一個引數 −

  • *FILE stream: 用於標識要關閉的流的 FILE 物件的指標。此指標由以下函式獲取:fopen、freopen 或 tmpfile。

返回值

如果成功關閉檔案,則函式返回 0。如果關閉檔案時發生錯誤,則返回 EOF(通常為 -1)。設定 errno 變數來指示錯誤。

示例 1:寫入資料後關閉檔案

此示例展示如何使用 fclose 向檔案中寫入資料,然後關閉檔案。

以下是 C 庫 fclose() 函式的演示。

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }
   fprintf(file, "Hello, World!\n");
   if (fclose(file) == EOF) {
       perror("Error closing file");
       return 1;
   }
   printf("File closed successfully.\n");
   return 0;
}


輸出

以上程式碼產生以下結果−

File closed successfully.

示例 2:處理檔案關閉錯誤

此示例處理關閉檔案失敗的情況,演示了適當的錯誤處理。

#include <stdio.h>
#include <errno.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }
   // Intentionally causing an error for demonstration (rare in practice)
   if (fclose(file) != 0) {
       perror("Error closing file");
       return 1;
   }
   // Trying to close the file again to cause an error
   if (fclose(file) == EOF) {
       perror("Error closing file");
       printf("Error code: %d\n", errno);
       return 1;
   }
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果 −

Error closing file: Bad file descriptor
Error code: 9
廣告