std::filesystem::copy不能用于需进度通知的同步拷贝,因其为原子操作且无中间状态;必须手动分块读写并回调,注意文件打开检查、目录预创建、缓冲区大小选择及错误处理。

同步拷贝为什么不能直接用 std::filesystem::copy
因为 std::filesystem::copy 是原子操作,不提供中间进度通知。它要么成功,要么失败,期间无法获取已拷贝字节数或触发回调。如果你需要实时进度条、暂停/取消支持或大文件友好行为,必须手动读写缓冲区。
核心做法:分块读取 + 写入 + 回调触发
本质就是打开源文件和目标文件,循环 read 一段数据(比如 64KB),write 这段数据,然后调用用户传入的回调函数,并传入当前已拷贝字节数和总大小。关键点在于:
- 使用
std::ifstream(std::ios::binary | std::ios::ate)获取源文件大小,避免先seekg(0, std::ios::end)再seekg(0)的两次 seek - 缓冲区用
std::vector<char></char>分配,大小建议 64KB–1MB;太小导致系统调用频繁,太大可能吃内存 - 每次
read后检查ifs.gcount(),它返回实际读到的字节数(最后一块可能不足缓冲区大小) - 写入后立即
ofs.flush()可选,但对进度回调无影响;真正影响的是读写是否阻塞或出错
容易踩的坑:错误处理与边界条件
同步拷贝看似简单,但实际出错路径多,且容易静默失败:
组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。
-
std::ifstream构造失败(路径不存在、权限不足)不会抛异常,需检查ifs.is_open() == false -
std::ofstream创建目录失败 ——std::filesystem::create_directories必须提前调用,否则ofs构造失败且不报具体原因 - 总大小为 0 时,
ifs.seekg(0, std::ios::end)可能返回 0,但后续read仍要执行一次(空读),需确保回调至少被调用一次 - Windows 下路径含中文或长路径(>260 字符)需启用
\?前缀,否则std::filesystem可能静默截断 - 回调函数里抛异常会直接终止拷贝 —— 建议文档注明“回调内请勿抛异常”,或用
noexcept声明
一个最小可行示例(C++17,含进度回调)
void copy_with_progress(
const std::filesystem::path& src,
const std::filesystem::path& dst,
std::function<void uint64_t> progress_cb) {
std::ifstream ifs(src, std::ios::binary | std::ios::ate);
if (!ifs.is_open()) throw std::runtime_error("open src failed: " + src.string());
<pre class="brush:php;toolbar:false;">uint64_t total = static_cast<uint64_t>(ifs.tellg());
ifs.seekg(0, std::ios::beg);
std::filesystem::create_directories(dst.parent_path());
std::ofstream ofs(dst, std::ios::binary);
if (!ofs.is_open()) throw std::runtime_error("open dst failed: " + dst.string());
std::vector<char> buf(64 * 1024);
uint64_t done = 0;
while (done (ifs.gcount());
if (n == 0) break; // eof or error
ofs.write(buf.data(), n);
done += n;
progress_cb(done, total);
}
if (done != total) {
throw std::runtime_error("copy incomplete: " + src.string());
}</char></uint64_t>
}
注意:progress_cb 在每次写入后立刻调用,不是按时间间隔,所以小文件可能回调密集;如果 UI 端需要限频,应在回调内部做节流,而不是在拷贝逻辑里加 sleep。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










