std::filesystem::copy_file
来自 cppreference.cn
< cpp | filesystem
定义于头文件 <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 起) |
bool copy_file( const std::filesystem::path& from, const std::filesystem::path& to, |
(3) | (自 C++17 起) |
bool copy_file( const std::filesystem::path& from, const std::filesystem::path& to, |
(4) | (自 C++17 起) |
1,2) 默认情况,等效于将
copy_options::none
用作 options 的 (3,4)。3,4) 将单个文件从 from 复制到 to,使用 options 指示的复制选项。 如果在 copy_options 选项组中存在多个选项(即使在与 filesystem::copy_file 无关的组中),则行为未定义。
- 如果 !filesystem::is_regular_file(from) (因为源文件不存在或因为它不是常规文件),则报告错误。
- 否则,如果目标文件不存在,
- 将 from 解析到的文件的内容和属性复制到 to 解析到的文件(会跟随符号链接)。
- 否则,如果目标文件已存在,
- 如果以下任何一项为真,则报告错误
- to 和 from 由 filesystem::equivalent(from, to) 确定为相同;
- to 不是常规文件,由 !filesystem::is_regular_file(to) 确定;
- 在 options 中未设置 filesystem::copy_file 控制选项。
- 否则,如果在 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) 在底层 OS API 错误时抛出 std::filesystem::filesystem_error,并使用 from 作为第一个路径参数,to 作为第二个路径参数,以及 OS 错误代码作为错误代码参数构造。
[编辑] 注意
这些函数最多涉及一次直接或间接调用 filesystem::status(to)(既用于确定文件是否存在,也用于 filesystem::copy_options::update_existing
选项,及其上次写入时间)。
当 filesystem::copy_file 用于复制目录时,会报告错误:为此使用 filesystem::copy。
filesystem::copy_file 跟随符号链接:为此使用 filesystem::copy_symlink 或 filesystem::copy 以及 filesystem::copy_options::copy_symlinks
。
[编辑] 示例
运行此代码
#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"); // 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"
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 3014 | C++17 | error_code 重载标记为 noexcept 但可以分配内存 |
noexcept 已移除 |
[编辑] 参见
(C++17) |
指定复制操作的语义 (枚举) |
(C++17) |
复制符号链接 (函数) |
(C++17) |
复制文件或目录 (函数) |