
- 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 庫 - fopen() 函式
C 庫函式 FILE *fopen(const char *filename, const char *mode) 使用給定的模式開啟 `filename` 指向的檔名。它開啟一個檔案並返回一個指向 FILE 物件的指標,該指標可用於訪問檔案。
語法
以下是 C 庫函式 fopen() 的語法:
FILE *fopen(const char *filename, const char *mode);
引數
此函式接受以下引數:
- filename:表示要開啟的檔名的字串。這可以包括絕對路徑或相對路徑。
- mode:表示應以何種模式開啟檔案的字串。常用模式包括:
- "r":以只讀方式開啟。檔案必須存在。
- "w":以寫入方式開啟。建立空檔案或截斷現有檔案。
- "a":以追加方式開啟。將資料寫入檔案末尾。如果檔案不存在則建立檔案。
- "r+":以讀寫方式開啟。檔案必須存在。
- "w+":以讀寫方式開啟。建立空檔案或截斷現有檔案。
- "a+":以讀寫和追加方式開啟。如果檔案不存在則建立檔案。
返回值
如果檔案成功開啟,fopen 函式返回一個 FILE 指標。如果無法開啟檔案,則返回 NULL。
示例 1:讀取檔案
此示例以讀取模式開啟名為 example.txt 的檔案,並將內容逐個字元列印到控制檯。
以下是 C 庫 fopen() 函式的示例。
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } char ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }
輸出
以上程式碼產生以下結果:
(Contents of example.txt printed to the console)
示例 2:追加到檔案
在這裡,我們以追加模式開啟名為 log.txt 的檔案,在檔案末尾新增新的日誌條目,然後關閉檔案。
#include <stdio.h> int main() { FILE *file = fopen("log.txt", "a"); if (file == NULL) { perror("Error opening file"); return 1; } const char *log_entry = "Log entry: Application started"; fprintf(file, "%s\n", log_entry); fclose(file); return 0; }
輸出
執行上述程式碼後,我們得到以下結果:
(log.txt contains the new log entry "Log entry: Application started" appended to any existing content)
廣告