
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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
廣告