Roi*_*ton 6 c++ filesystems cross-platform
使用C++,是否可以递归地将文件和目录从一个路径复制到另一个路径
考虑以下文件系统
src/fileInRoot
src/sub_directory/
src/sub_directory/fileInSubdir
Run Code Online (Sandbox Code Playgroud)
我要复制
从src另一个目录target.
我创建了一个新问题,因为我发现的问题是特定于平台的,不包括过滤:
Roi*_*ton 12
是的,可以使用除了标准C++之外的其他任何东西来复制一个完整的目录结构 ......从C++ 17开始std::filesystem,包含它std::filesystem::copy.
1)复制所有文件可以使用copy_options::recursive:
// Recursively copies all files and folders from src to target and overwrites existing files in target.
void CopyRecursive(const fs::path& src, const fs::path& target) noexcept
{
try
{
fs::copy(src, target, fs::copy_options::overwrite_existing | fs::copy_options::recursive);
}
catch (std::exception& e)
{
std::cout << e.what();
}
}
Run Code Online (Sandbox Code Playgroud)
2)使用过滤器复制文件的某个子集,recursive_directory_iterator可以使用:
// 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();
}
}
Run Code Online (Sandbox Code Playgroud)
当调用第二种方法时
#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);
}
Run Code Online (Sandbox Code Playgroud)
并且给定的文件系统位于进程的工作目录中,然后结果是
target/sub_directory/
target/sub_directory/fileInSubdir
Run Code Online (Sandbox Code Playgroud)
您还可以传递copy_optionsas参数以CopyRecursive()获得更大的灵活性.
上面使用的一些函数的列表std::filesystem:
relative()减去路径和heeds符号链接(它使用path::lexically_relative()和weakly_canonical())create_directories() 为给定路径中尚不存在的每个元素创建一个目录current_path() 返回(或更改)当前工作目录的绝对路径path::stem() 返回没有最终扩展名的文件名path::generic_string() 给出具有平台无关目录分隔符的窄字符串 /对于生产代码,我建议将错误处理从实用程序功能中拉出来.对于错误处理,std::filesystem提供两种方法:
还要考虑到,std::filesystem可能并非在所有平台上都可用
如果实现无法访问分层文件系统,或者它没有提供必要的功能,则文件系统库工具可能不可用.如果底层文件系统不支持某些功能,则可能无法使用某些功能(例如,FAT文件系统缺少符号链接并禁止多个硬链接).在这些情况下,必须报告错误.