使用C++ fstream实现文件复制需通过ifstream读取源文件,ofstream写入目标文件,以二进制模式打开文件,分块读写缓冲区并检查文件状态,确保复制成功。
要使用C++中的
fstream
实现文件复制功能,核心思路是通过
ifstream
读取源文件内容,再通过
ofstream
将读取的数据写入目标文件。整个过程可以逐字符、按块或使用流操作符完成。
包含必要的头文件
C++标准库中用于文件操作的类定义在
<fstream>
中,同时需要
<iostream>
处理错误输出:
#include <fstream>
#include <iostream>
打开源文件和目标文件
使用
ifstream
打开源文件,确保以二进制模式(
std::ios::binary
)读取,避免文本模式对换行符等字符的转换。同样,
ofstream
也应以二进制模式写入:
std::ifstream src(“source.txt”, std::ios::binary);
std::ofstream dest(“copy.txt”, std::ios::binary);
检查文件是否成功打开,防止后续操作失败:
立即学习“C++免费学习笔记(深入)”;
if (!src || !dest) {
std::cerr << “无法打开文件!” << std::endl;
return 1;
}
复制文件内容
有多种方式复制数据,推荐使用缓冲区按块读写,效率更高。例如,每次读取4096字节:
src.seekg(0, std::ios::end);
size_t size = src.tellg();
src.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
src.read(buffer.data(), size);
dest.write(buffer.data(), size);
或者更安全地分块处理大文件:
char buffer[4096];
while (src.read(buffer, sizeof(buffer)) || src.gcount() > 0) {
dest.write(buffer, src.gcount());
}
完整示例代码
以下是一个完整的函数,实现文件复制:
bool copyFile(const std::string& source, const std::string& destination) {
std::ifstream src(source, std::ios::binary);
std::ofstream dest(destination, std::ios::binary);
if (!src || !dest) {
return false;
}
char buffer[4096];
while (src.read(buffer, sizeof(buffer)) || src.gcount() > 0) {
dest.write(buffer, src.gcount());
}
return src.eof() && !src.fail() && !dest.fail();
}
调用时传入源路径和目标路径即可:
int main() {
if (copyFile(“a.txt”, “b.txt”)) {
std::cout << “复制成功!” << std::endl;
} else {
std::cout << “复制失败!” << std::endl;
}
return 0;
}
基本上就这些。只要注意以二进制模式操作、检查文件状态、合理使用缓冲区,就能可靠地完成文件复制。不复杂但容易忽略细节。
ai c++ ios 标准库 EOF String if while include const bool char int cerr ofstream ifstream fstream copy ios