| 模式 | 說明 |
"r" | 唯讀,檔案必須存在 |
"w" | 唯寫,截斷現有檔案或建立新檔 |
"a" | 附加寫入,檔案不存在則建立 |
"r+" | 讀寫,檔案必須存在 |
"w+" | 讀寫,截斷或建立 |
"a+" | 讀寫,附加模式 |
二進位模式在模式字串後加 b (如 "rb"),避免 Windows 換行轉換。
完整寫入範例
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int main()
{
FILE *fp = fopen("out.txt", "w");
if (!fp) {
perror("fopen");
return EXIT_FAILURE;
}
for (int x = 1; x <= MAX; x++)
fprintf(fp, "%d\n", x);
if (fclose(fp) != 0) {
perror("fclose");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
讀取範例
FILE *fp = fopen("out.txt", "r");
if (!fp) return 1;
int val;
while (fscanf(fp, "%d", &val) == 1)
printf("讀到: %d\n", val);
fclose(fp);
錯誤處理重點
- 永遠檢查
fopen 返回值是否為 NULL。
- 寫入後檢查
fclose 返回值 (非 0 表示錯誤)。
- 使用
ferror(fp) 檢測流錯誤,feof(fp) 檢測檔案結尾。
- 上一篇文章: NYOJ 214 最長單調遞增子序列:O(n log n) 二分優化 DP 詳解
- 下一篇文章: C語言 scanf 格式字串中 * 號抑制賦值用法
Copyright ©
程式碼之家 All Rights Reserved