C文件I/O ? 創(chuàng)建、打開、讀取、寫入和關閉文件
C文件管理
文件可用于存儲大量持久數據。像許多其他語言一樣,’C’提供以下文件管理函數:
- 創(chuàng)建文件打開文件讀取文件向文件寫入關閉文件
以下是’C’中最重要的文件管理函數:
| 函數 | 目的 |
|---|---|
| fopen () | 創(chuàng)建文件或打開現(xiàn)有文件 |
| 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;
}
登錄后復制
以上就是C程序將一個文件的內容復制到另一個文件中的詳細內容,更多請關注www.xfxf.net其它相關文章!






