std::experimental::filesystem::copy_file
来自 cppreference.cn
< cpp | experimental | fs
定义于头文件 <experimental/filesystem> |
||
bool copy_file( const path& from, const path& to ); bool copy_file( const path& from, const path& to, error_code& ec ); |
(1) | (文件系统 TS) |
bool copy_file( const path& from, const path& to, copy_options options ); bool copy_file( const path& from, const path& to, copy_options options, error_code& ec ); |
(2) | (文件系统 TS) |
1) 默认情况,等同于使用
copy_options::none
作为 options 的 (2)。2) 使用 options 指示的复制选项,将单个文件从 from 复制到 to。如果在 options 中存在任何 copy_options 选项组中(即使是不与
copy_file
相关的组)有多个选项,则行为未定义。- 如果目标文件不存在,
- 将 from 解析到的文件的内容和属性复制到 to 解析到的文件(符号链接被跟踪)。
- 否则,如果目标文件已存在
- 如果 to 和 from 通过 equivalent(from, to) 确定为相同,则报告错误。
- 否则,如果在 options 中没有设置任何 copy_file 控制选项,则报告错误。
- 否则,如果在 options 中设置了
copy_options::skip_existing
,则不执行任何操作。 - 否则,如果在 options 中设置了
copy_options::overwrite_existing
,则将 from 解析到的文件的内容和属性复制到 to 解析到的文件。 - 否则,如果在 options 中设置了
copy_options::update_existing
,则仅当 from 比 to 新时才复制文件,如 last_write_time() 所定义。
如果发生错误,非抛出重载返回 false。
目录 |
[编辑] 参数
from | - | 源文件的路径 |
to | - | 目标文件的路径 |
ec | - | 非抛出重载中用于错误报告的出参 |
[编辑] 返回值
如果文件已复制,则为 true,否则为 false。
[编辑] 异常
不接受 error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error,该异常以 from 作为第一个参数,to 作为第二个参数,OS 错误码作为错误码参数构造。如果内存分配失败,可能会抛出 std::bad_alloc。接受 error_code& 参数的重载在 OS API 调用失败时将其设置为 OS API 错误码,并且在没有错误发生时执行 ec.clear()。此重载具有noexcept 规范:
noexcept
[编辑] 注意
这些函数最多包含一次直接或间接调用 status(to)(用于确定文件是否存在,以及对于 copy_options::update_existing
选项,确定其最后写入时间)。
当使用 copy_file
复制目录时会报告错误:请使用 copy。
copy_file
遵循符号链接:请使用 copy_symlink 或 copy 并结合 copy_options::copy_symlinks
。
[编辑] 示例
运行此代码
#include <experimental/filesystem> #include <fstream> #include <iostream> namespace fs = std::experimental::filesystem; int main() { fs::create_directory("sandbox"); std::ofstream("sandbox/file1.txt").put('a'); fs::copy_file("sandbox/file1.txt", "sandbox/file2.txt"); // now there are two files in 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'; // fail to copy directory 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"
[编辑] 另请参阅
指定复制操作的语义 (枚举) | |
复制一个符号链接 (函数) | |
复制文件或目录 (函数) |