Namespaces
Variants

std::filesystem:: copy_file

From cppreference.net
定义于头文件 <filesystem>
bool copy_file ( const std:: filesystem :: path & from,
const std:: filesystem :: path & to ) ;
(1) (C++17 起)
bool copy_file ( const std:: filesystem :: path & from,

const std:: filesystem :: path & to,

std:: error_code & ec ) ;
(2) (C++17 起)
(3) (C++17 起)
(4) (C++17 起)
1,2) 默认情况,等同于使用 copy_options::none 作为 options (3,4) 形式。
3,4) 将单个文件从 from 复制到 to ,使用由 options 指定的复制选项。如果在 options 中任何 copy_options 选项组存在多个选项(即使是不与 filesystem::copy_file 相关的组),则行为未定义。
  • from 解析到的文件内容和属性复制到 to 解析到的文件(会跟随符号链接)。
  • 否则,如果目标文件已存在,
  • 如果以下任一条件为真,则报告错误:
  • 否则,如果在 options 中设置了 copy_options::skip_existing ,则不执行任何操作。
  • 否则,如果在 options 中设置了 copy_options::overwrite_existing ,则将 from 解析到的文件内容和属性复制到 to 解析到的文件。
  • 否则,如果在 options 中设置了 copy_options::update_existing ,则仅当 from to 新时(根据 filesystem::last_write_time() 定义)才复制文件。

无抛出重载在出现错误时返回 false

目录

参数

from - 源文件路径
to - 目标文件路径
ec - 非抛出重载中用于错误报告的输出参数

返回值

true 表示文件已成功复制, false 表示复制失败。

异常

任何未标记为 noexcept 的重载在内存分配失败时可能抛出 std::bad_alloc

1,3) 当底层操作系统API出错时抛出 std::filesystem::filesystem_error ,该异常以 from 作为第一个路径参数, to 作为第二个路径参数,并以操作系统错误代码作为错误码参数构造。
2,4) 若操作系统 API 调用失败,将 std:: error_code & 参数设置为操作系统 API 错误码;若未发生错误,则执行 ec. clear ( )

注释

这些函数最多涉及一次直接或间接调用 filesystem::status(to) (既用于确定文件是否存在,也用于 filesystem::copy_options::update_existing 选项的最近写入时间判断)。

当使用 filesystem::copy_file 复制目录时会报错:请改用 filesystem::copy 实现该操作。

filesystem::copy_file 会跟随符号链接:如需此功能请使用 filesystem::copy_symlink 或带有 filesystem::copy_options::copy_symlinks 选项的 filesystem::copy

示例

#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
int main()
{
    fs::create_directory("sandbox");
    std::ofstream("sandbox/file1.txt").put('a');
    fs::copy_file("sandbox/file1.txt", "sandbox/file2.txt");
    // 此时沙盒目录中存在两个文件:
    std::cout << "file1.txt holds: "
              << std::ifstream("sandbox/file1.txt").rdbuf() << '\n';
    std::cout << "file2.txt holds: "
              << std::ifstream("sandbox/file2.txt").rdbuf() << '\n';
    // 尝试复制目录(将失败)
    fs::create_directory("sandbox/abc");
    try
    {
        fs::copy_file("sandbox/abc", "sandbox/def");
    }
    catch (fs::filesystem_error& e)
    {
        std::cout << "Could not copy sandbox/abc: " << e.what() << '\n';
    }
    fs::remove_all("sandbox");
}

可能的输出:

file1.txt holds: a
file2.txt holds: a
Could not copy sandbox/abc: copy_file: Is a directory: "sandbox/abc", "sandbox/def"

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 3014 C++17 error_code 重载标记为 noexcept 但可能分配内存 移除 noexcept

参见

指定复制操作的语义
(枚举)
复制符号链接
(函数)
(C++17)
复制文件或目录
(函数)