C語言程式:如何將一個檔案的內容複製到另一個檔案?
C語言檔案I/O − 建立、開啟、讀取、寫入和關閉檔案
C語言檔案管理
檔案可以用來儲存大量的永續性資料。像許多其他語言一樣,'C'提供了以下檔案管理功能:
- 建立檔案
- 開啟檔案
- 讀取檔案
- 寫入檔案
- 關閉檔案
以下是C語言中最重要的檔案管理函式:
函式 | 用途 |
---|---|
fopen () | 建立檔案或開啟現有檔案 |
fclose () | 關閉檔案 |
fprintf () | 將資料塊寫入檔案 |
fscanf () | 從檔案讀取資料塊 |
getc () | 從檔案讀取單個字元 |
putc () | 將單個字元寫入檔案 |
getw () | 從檔案讀取整數 |
putw () | 將整數寫入檔案 |
fseek () | 將檔案指標的位置設定到指定位置 |
ftell () | 返回檔案指標的當前位置 |
rewind () | 將檔案指標設定到檔案開頭 |
Input: sourcefile = x1.txt targefile = x2.txt Output: File copied successfully.
說明
在這個程式中,我們將一個檔案複製到另一個檔案。首先,你需要指定要複製的檔案。我們將以“讀取”模式開啟要複製的檔案,並以“寫入”模式開啟目標檔案。
示例
#include <iostream> #include <stdlib.h> using namespace std; int main() { char ch;// source_file[20], target_file[20]; FILE *source, *target; char source_file[]="x1.txt"; char target_file[]="x2.txt"; source = fopen(source_file, "r"); if (source == NULL) { printf("Press any key to exit...
"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...
"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.
"); fclose(source); fclose(target); return 0; }
廣告