C++ 实现文件拷贝:
bool copyFile(const std::string& source, const std::string& target)
{
bool success = true;
try
{
// mkdir(),父目录必须存在
// 如果目录已经存返回 false,OS API 调用失败时会抛出异常
if (!fs::create_directories(fs::path(target).parent_path()))
{
std::cerr << "Target directory is existed. " << std::endl;
LOG_STREAM(user, info) << "Target directory is existed. ";
}
if (!fs::copy_file(source, target, fs::copy_options::overwrite_existing))
{
success = false;
}
} catch (std::filesystem::filesystem_error const& ex)
{
LOG_STREAM(user, warn) << "Failed to copy file: " << ex.what();
success = false;
}
return success;
}