std::filesystem::copy

定义于头文件 <filesystem>
void copy( const std::filesystem::path& from,

           const std::filesystem::path& to );
void copy( const std::filesystem::path& from,
           const std::filesystem::path& to,

           std::error_code& ec );
(1) (C++17 起)
void copy( const std::filesystem::path& from,

           const std::filesystem::path& to,
           std::filesystem::copy_options options );
void copy( const std::filesystem::path& from,
           const std::filesystem::path& to,
           std::filesystem::copy_options options,

           std::error_code& ec );
(2) (C++17 起)

复制文件与目录,带一些选项

1) 默认,等价于以 copy_options::none 为选项的 (2)
2) 复制文件或目录 from 到文件或目录 to ,使用 options 所指定的复制选项。若 options 中存在 copy_options 任一选项组中多于一个的选项(即使在无关乎 copycopy_file 组中)

行为如下:

目录

参数

from - 源文件、目录或符号链接的路径
to - 目标文件、目录或符号链接的路径
ec - 不抛出重载中报告错误的输出参数

返回值

(无)

异常

不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一参数 from,第二参数 to 和作为错误码参数的 OS 错误码构造。若内存分配失败则可能抛出 std::bad_alloc 。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear()

注意

复制目录时的默认行为是非递归复制:复制文件,但不复制子目录:

// 给定
// /dir1 含有 /dir1/file1 、 /dir1/file2 、 /dir1/dir2
// 而 /dir1/dir2 含有 /dir1/dir2/file3
std::filesystem::copy("/dir1", "/dir3");
// 之后
// 创建 /dir3 (拥有 /dir1 的属性)
// /dir1/file1 被复制到 /dir3/file1
// /dir1/file2 被复制到 /dir3/file2

而带有 copy_options::recursive 时,亦复制子目录,递归地带有其内容。

// ……但在下一句后
std::filesystem::copy("/dir1", "/dir3", std::filesystem::copy_options::recursive);
// 创建 /dir3 (拥有 /dir1 的属性)
// /dir1/file1 被复制到 /dir3/file1
// /dir1/file2 被复制到 /dir3/file2
// 创建 /dir3/dir2 (拥有 /dir1/dir2 的属性)
// /dir1/dir2/file3 被复制到 /dir3/dir2/file3


示例

#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::create_directories("sandbox/dir/subdir");
    std::ofstream("sandbox/file1.txt").put('a');
    fs::copy("sandbox/file1.txt", "sandbox/file2.txt"); // 复制文件
    fs::copy("sandbox/dir", "sandbox/dir2"); // 复制目录(非递归)
    // sandbox 保有 2 个文件及 2 个目录,其中之一拥有子目录
    // sandbox/file1.txt
    // sandbox/file2.txt
    // sandbox/dir2
    // sandbox/dir
    //    sandbox/dir/subdir
    fs::copy("sandbox", "sandbox/copy", fs::copy_options::recursive);
    // sandbox/copy 保有上述文件和子目录的副本
    fs::remove_all("sandbox");
}


参阅

(C++17)
指定复制操作的语义
(枚举)
(C++17)
复制一个符号链接
(函数)
(C++17)
复制文件内容
(函数)

版本历史

  • (当前 | 先前 2017年4月30日 (日) 19:31Fruderica讨论 | 贡献 . . (5,623字节) (-3). . (撤销)
  • 当前 | 先前) 2017年4月30日 (日) 19:12Fruderica讨论 | 贡献. . (5,626字节) (+5,626). . (以“{{cpp/filesystem/title|copy}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | num=1 | since=c++17 | 1= void copy( const std::filesystem::...”为内容创建页面)