Namespaces
Variants

std::filesystem:: copy_options

From cppreference.net
定义于头文件 <filesystem>
enum class copy_options {

none = /* 未指定 */ ,
skip_existing = /* 未指定 */ ,
overwrite_existing = /* 未指定 */ ,
update_existing = /* 未指定 */ ,
recursive = /* 未指定 */ ,
copy_symlinks = /* 未指定 */ ,
skip_symlinks = /* 未指定 */ ,
directories_only = /* 未指定 */ ,
create_symlinks = /* 未指定 */ ,
create_hard_links = /* 未指定 */

} ;
(C++17 起)

此类型表示控制 copy() copy_file() 函数行为的可用选项。

copy_options 满足 BitmaskType 的要求(这意味着位运算符 operator & operator | operator ^ operator~ operator & = operator | = operator ^ = 已为此类型定义)。 none 表示空位掩码;其他每个枚举符均表示一个独立的位掩码元素。

成员常量

在以下各选项组中最多只能存在一个复制选项,否则复制函数的行为将是未定义的。

成员常量 含义
控制 copy_file() 当文件已存在时的选项
none 报告错误(默认行为)。
skip_existing 保留现有文件,且不报告错误。
overwrite_existing 替换现有文件。
update_existing 仅当现有文件比被复制文件更旧时进行替换。
控制 copy() 对于子目录影响的选项
none 跳过子目录(默认行为)。
recursive 递归复制子目录及其内容。
控制 copy() 对于符号链接影响的选项
none 跟随符号链接(默认行为)。
copy_symlinks 将符号链接作为链接复制,而非它们指向的文件。
skip_symlinks 忽略符号链接。
控制 copy() 复制类型的选项
none 复制文件内容(默认行为)。
directories_only 仅复制目录结构,不复制任何非目录文件。
create_symlinks 创建指向原始文件的符号链接而非文件副本。注意:除非目标路径在当前目录下,否则源路径必须是绝对路径。
create_hard_links 创建与原始文件指向相同文件的硬链接而非文件副本。

示例

#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
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"); // 复制目录(非递归)
    const auto copyOptions = fs::copy_options::update_existing
                           | fs::copy_options::recursive
                           | fs::copy_options::directories_only
                           ;
    fs::copy("sandbox", "sandbox_copy", copyOptions); 
    static_cast<void>(std::system("tree"));
    fs::remove_all("sandbox");
    fs::remove_all("sandbox_copy");
}

可能的输出:

.
├── sandbox
│   ├── dir
│   │   └── subdir
│   ├── dir2
│   ├── file1.txt
│   └── file2.txt
└── sandbox_copy
    ├── dir
    │   └── subdir
    └── dir2
8 directories, 2 files

参见

(C++17)
复制文件或目录
(函数)
(C++17)
复制文件内容
(函数)