定义于头文件
<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, |
(2) | (C++17 起) |
copy_options::none
为 options
的 (2) from
到 to
复制单个文件,使用 options
所指示的复制选项。若 options
中存在任一 copy_options 选项组中多于一个的选项,则行为未定义(即使在无关乎 copy_file
的组中)。
from
所解析到的文件的内容及属性到 to
所解析到者(跟随符号链接)
to
与 from
相同,如 equivalent(from, to) 所确定;
to
不是常规文件,如 !is_regular_file(to) 所确定
copy_file
控制选项设置于 options
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_symlink 或 copy 带 copy_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)
|
复制文件或目录 (函数) |