如何递归复制文件和目录

Roi*_*ton 6 c++ filesystems cross-platform

使用C++,是否可以递归地将文件和目录从一个路径复制到另一个路径

  • 无需使用任何额外的库?
  • 并具有平台独立功能?

考虑以下文件系统

src/fileInRoot
src/sub_directory/
src/sub_directory/fileInSubdir
Run Code Online (Sandbox Code Playgroud)

我要复制

  1. 所有文件和目录或
  2. 某些文件和目录

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:


对于生产代码,我建议将错误处理从实用程序功能中拉出来.对于错误处理,std::filesystem提供两种方法:

  1. std::exception/的例外情况std::filesystem::filesystem_error
  2. 和错误代码std::error_code.

还要考虑到,std::filesystem可能并非在所有平台上都可用

如果实现无法访问分层文件系统,或者它没有提供必要的功能,则文件系统库工具可能不可用.如果底层文件系统不支持某些功能,则可能无法使用某些功能(例如,FAT文件系统缺少符号链接并禁止多个硬链接).在这些情况下,必须报告错误.