將來源檔案(如 `ch1.txt`)內容完整複製到目標檔案(`ch2.txt`),需處理檔案開啟失敗、讀寫錯誤等異常情況。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *in, *out;
char ch;
// 開啟來源檔案(唯讀模式)
if ((in = fopen("d:\\txt\\ch1.txt", "r")) == NULL) {
printf("無法開啟來源檔案 ch1.txt!\n");
exit(1);
}
// 開啟目標檔案(寫入模式,會覆蓋舊內容)
if ((out = fopen("d:\\txt\\ch2.txt", "w")) == NULL) {
printf("無法建立目標檔案 ch2.txt!\n");
fclose(in); // 關閉已開啟的來源檔案
exit(1);
}
// 逐字元複製
while ((ch = fgetc(in)) != EOF) {
fputc(ch, out);
}
// 關閉檔案並檢查錯誤
if (fclose(in) != 0) {
perror("關閉來源檔案失敗");
}
if (fclose(out) != 0) {
perror("關閉目標檔案失敗");
}
printf("檔案複製完成。\n");
return 0;
}
fopen(path, mode):開啟檔案,回傳 `FILE*` 指標,失敗回傳 `NULL`。模式 `"r"` 唯讀,`"w"` 寫入(截斷/建立)。fgetc(fp):讀取單一字元,成功回傳字元值(`unsigned char` 轉 `int`),檔案結束或錯誤回傳 `EOF`(通常為 -1)。fputc(ch, fp):寫入單一字元,成功回傳寫入的字元,失敗回傳 `EOF`。fclose(fp):關閉檔案並刷新緩衝區,成功回傳 0,失敗回傳 `EOF`。逐字元複製對大檔案效能較差,建議使用緩衝區:
#define BUFSIZE 4096
char buffer[BUFSIZE];
size_t bytes;
while ((bytes = fread(buffer, 1, BUFSIZE, in)) > 0) {
if (fwrite(buffer, 1, bytes, out) != bytes) {
perror("寫入錯誤");
break;
}
}
此法大幅減少系統呼叫次數,為實務常用做法。