std::filesystem::copy_file

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

                const std::filesystem::path& to );
bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,

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

                const std::filesystem::path& to,
                std::filesystem::copy_options options );
bool copy_file( 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::noneoptions(2)
2)fromto 复制单个文件,使用 options 所指示的复制选项。若 options 中存在任一 copy_options 选项组中多于一个的选项,则行为未定义(即使在无关乎 copy_file 的组中)。
  • 复制 from 所解析到的文件的内容及属性到 to 所解析到者(跟随符号链接)
  • 若下列之一为真则报告错误:
  • 否则,若 copy_options::skip_existing 设置于 options ,则不做任何事
  • 否则,若 copy_options::overwrite_existing 设置于 options ,则复制 from 所解析到的文件的内容及属性到 to 所解析到者
  • 否则,若 copy_options::update_existing 设置于 options ,则仅若 from 新于 to 才复制,如 last_write_time() 所定义

若错误发生,则不抛出重载返回 false

目录

参数

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

返回值

若文件被复制则返回 true ,否则返回 false

异常

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

注意

函数最多引入一次对 status(to) 的直接或间接调用(均用于确定文件是否存在,及对于 copy_options::update_existing 选项,确定其最后写入时间)

copy_file 被用于复制目录时报告错误:用 copy 复制它们。

copy_file 跟随符号链接:用 copy_symlinkcopycopy_options::copy_symlinks 复制它们。

示例

#include <fstream>
#include <iostream>
#include <filesystem>
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");
 
    // 现在 sandbox 中有二个文件:
    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++17)
指定复制操作的语义
(枚举)
(C++17)
复制一个符号链接
(函数)
(C++17)
复制文件或目录
(函数)

版本历史

  • (当前 | 先前) 2017年4月30日 (日) 19:40Fruderica讨论 | 贡献. . (4,354字节) (+4,354). . (以“{{cpp/filesystem/title|copy_file}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | num=1 | since=c++17 | 1= bool copy_file( const std::fi...”为内容创建页面)