如何递归复制文件和目录 [英] How to recursively copy files and directories

查看:46
本文介绍了如何递归复制文件和目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  • 而不必使用任何附加库?
  • 并且具有独立于平台的功能?

考虑以下文件系统

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

我要复制

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

src到另一个目录target


我已经创建了一个新问题,因为我找到的问题是特定于平台的,不包括筛选:

推荐答案

可以,只使用STD 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();
    }
}
  1. 要使用过滤复制文件的某个子集,可以使用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, targetParentPath, 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_optionsAs参数传递给CopyRecursive()以获得更大的灵活性。


上面使用的std::filesystem中的一些函数列表:


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

  1. 异常,std::exception/std::filesystem::filesystem_error
  2. 和错误代码std::error_code

还应考虑,std::filesystem可能not be available on all platforms

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

这篇关于如何递归复制文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆