// Recursively copies those files and folders from src to target which matches
// predicate, and overwrites existing files in target.
void CopyRecursive(const fs::path& src, const fs::path& target,
const std::function<bool(fs::path)>& predicate /* or use template */) noexcept
{
try
{
for (const auto& dirEntry : fs::recursive_directory_iterator(src))
{
const auto& p = dirEntry.path();
if (predicate(p))
{
// Create path in target, if not existing.
const auto relativeSrc = fs::relative(p, src);
const auto targetParentPath = target / relativeSrc.parent_path();
fs::create_directories(targetParentPath);
// Copy to the targetParentPath which we just created.
fs::copy(p, targetPath, fs::copy_options::overwrite_existing);
}
}
}
catch (std::exception& e)
{
std::cout << e.what();
}
}
当调用第二种方法时
#include <filesystem>
#include <iostream>
#include <functional>
namespace fs = std::filesystem;
int main()
{
const auto root = fs::current_path();
const auto src = root / "src";
const auto target = root / "target";
// Copy only those files which contain "Sub" in their stem.
const auto filter = [](const fs::path& p) -> bool
{
return p.stem().generic_string().find("Sub") != std::string::npos;
};
CopyRecursive(src, target, filter);
}
1 回答
Yes, it is possible to copy a complete directory structure 使用除了标准C之外的其他内容......以C 17开头,其std::filesystem包括std::filesystem::copy .
1)可以使用copy_options::recursive复制所有文件:
2)要使用过滤器复制文件的某个子集,可以使用recursive_directory_iterator:
当调用第二种方法时
并且给定的文件系统位于进程的工作目录中,然后结果是
您还可以将
copy_options
作为参数传递给CopyRecursive()
,以获得更大的灵活性 .上面使用的
std::filesystem
中的一些函数列表:relative()减去路径和heeds符号链接(它使用path::lexically_relative()和weakly_canonical())
create_directories()为给定路径中尚不存在的每个元素创建一个目录
current_path()返回(或更改)当前工作目录的绝对路径
path::stem()返回没有最终扩展名的文件名
path::generic_string()给出了与平台无关的目录分隔符
/
的窄字符串对于 生产环境 代码,我建议将错误处理从实用程序功能中拉出来 . 对于错误处理,
std::filesystem
提供了两种方法:与std::exception / std::filesystem::filesystem_error
例外
和错误代码std::error_code .
还要考虑到
std::filesystem
可能not be available on all platforms