使用fstream按字节或块读写复制文件:通过ifstream读取源文件,ofstream写入目标文件,需检查文件打开状态,适用于小文件一次性读取。

在C++中复制文件内容有多种实现方式,可以根据需求选择合适的方法。常用的方法包括使用标准库中的 fstream 读写文件,或使用 std::filesystem(C++17 起)提供的现成函数。下面介绍几种常见的文件复制实现方法。
1. 使用 fstream 按字节或块读写复制文件
这是最基础的方式,通过 ifstream 读取源文件,ofstream 写入目标文件。
示例代码:
#include
#include
bool copyFile(const std::string& src, const std::2dstd::string& dest) {
std::ifstream source(src, std::ios::binary);
std::ofstream destination(dest, std::ios::binary);
if (!source || !destination) {
return false;
}
// 一次性读取整个文件(小文件适用)
destination << source.rdbuf();
source.close();
destination.close();
return true;
}
说明:使用 rdbuf() 可以高效地将源文件缓冲区内容写入目标流,适用于大多数情况,尤其是小到中等大小的文件。
2. 分块读取避免内存占用过高
对于大文件,建议使用固定大小的缓冲区逐块读写,避免一次性加载整个文件。
立即学习“C++免费学习笔记(深入)”;
示例代码:
bool copyFileInChunks(const std::string& src, const std::string& dest) {
std::ifstream source(src, std::ios::binary);
std::ofstream destination(dest, std::ios::binary);
if (!source || !destination) {
return false;
}
source.seekg(0, std::ios::end);
long long size = source.tellg();
source.seekg(0, std::ios::beg);
std::vector buffer(4096); // 4KB 缓冲区
while (source.read(buffer.data(), buffer.size())) {
destination.write(buffer.data(), buffer.size());
}
// 写入剩余部分
destination.write(buffer.data(), source.gcount());
source.close();
destination.close();
return true;
}
说明:这种方式更安全,适合处理大文件,防止内存溢出。
3. 使用 C++17 filesystem 直接复制
如果编译器支持 C++17,可以使用
#include
namespace fs = std::filesystem;
bool copyFileWithFs(const std::string& src, const std::string& dest) {
try {
fs::copy(fs::path(src), fs::path(dest),
fs::copy_options::overwrite_existing);
return true;
} catch (const fs::filesystem_error&) {
return false;
}
}
说明:该方法自动处理各种边界情况,支持覆盖、跳过已存在文件等选项,推荐在现代C++项目中使用。
4. 注意事项
进行文件复制时需注意以下几点:
- 始终检查文件是否成功打开,避免空流操作
- 使用 binary 模式复制可确保内容不被文本转换干扰(如换行符)
- 处理异常,特别是在 filesystem 方法中可能抛出异常
- 目标路径所在目录必须存在,否则复制会失败
基本上就这些。根据你的编译环境和需求选择合适的方法即可。小项目用 fstream,新项目推荐用 filesystem。











