C文件I / O-创建,打开,读取,写入和关闭文件
文件可用于存储大量持久性数据。与其他许多语言一样,“ C”提供了以下文件管理功能,
创建文件
开启档案
读取文件
写入文件
关闭档案
以下是“ C”中可用的最重要的文件管理功能,
功能 | 目的 |
---|---|
开张() | 创建文件或打开现有文件 |
fclose() | 关闭档案 |
fprintf() | 将数据块写入文件 |
fscanf() | 从文件中读取块数据 |
getc() | 从文件中读取单个字符 |
putc() | 将单个字符写入文件 |
getw() | 从文件中读取一个整数 |
putw() | 将整数写入文件 |
fseek() | 将文件指针的位置设置为指定位置 |
ftell() | 返回文件指针的当前位置 |
倒带() | 将文件指针设置在文件的开头 |
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...\n"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.\n"); fclose(source); fclose(target); return 0; }