如何递归复制文件和目录

时间:2018-07-19 20:44:58

标签: c++ filesystems cross-platform

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

  • 无需使用任何其他库?
  • 具有平台独立功能吗?

考虑以下文件系统

src/fileInRoot
src/sub_directory/
src/sub_directory/fileInSubdir

我要复制

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

src到另一个目录target


我创建了一个新问题,因为发现的问题是特定于平台的,并且不包含过滤器:

1 个答案:

答案 0 :(得分:8)

是的,可以使用std C ++来复制完整的目录结构 ...从C ++ 17及其包含std::filesystemstd::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();
    }
}

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();
    }
}

在调用第二种方法时

#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);
}

,给定的文件系统位于进程的工作目录中,则结果为

target/sub_directory/
target/sub_directory/fileInSubdir

您还可以将copy_options作为参数传递给CopyRecursive(),以提高灵活性。


std::filesystem中上面使用的一些功能的列表:


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

  1. 具有std::exception / std::filesystem::filesystem_error
  2. 的例外情况
  3. 以及带有std::error_code的错误代码。

还要考虑到std::filesystem可能not be available on all platforms

  

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