文件 IO
在 C 语言中,FILE
结构是标准 I/O 库中定义的一种数据结构,用于处理文件输入和输出。
FILE
结构是一种文件流的抽象,提供文件相关操作所需的信息和控制。
通常与 fopen
、fclose
、fread
、fwrite
、fseek
等函数一起使用。
如果你想将文件 source.txt
的内容复制到文件 destination.txt
,可以这样做:
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char buffer[1024];
size_t bytesRead;
// 以二进制读取模式打开源文件
sourceFile = fopen("source.txt", "rb");
// 检查源文件是否存在
if (sourceFile == NULL) {
printf("Error opening source file.\n");
return 1;
}
// 以二进制写入模式打开目标文件
destinationFile = fopen("destination.txt", "wb");
// 检查目标文件是否成功创建
if (destinationFile == NULL) {
printf("Error creating destination file.\n");
// 关闭源文件
fclose(sourceFile);
return 2;
}
// 使用 `fwrite` 将源文件的内容复制到目标文件
while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0) {
fwrite(buffer, 1, bytesRead, destinationFile);
}
// 关闭两个文件
fclose(sourceFile);
fclose(destinationFile);
return 0;
}
Loading...
> 此处输出代码运行结果