std::filesystem:: copy_file
|
定义于头文件
<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 起) |
copy_options::none
作为
options
的
(3,4)
形式。
- 如果 !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
。
注释
这些函数最多涉及一次直接或间接调用
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)
|
指定复制操作的语义
(枚举) |
|
(C++17)
|
复制符号链接
(函数) |
|
(C++17)
|
复制文件或目录
(函数) |