std::experimental::filesystem:: copy_file
|
定义于头文件
<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) |
copy_options::none
作为
options
的
(2)
形式。
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 表示复制失败。
异常
The overload that does not take an error_code & parameter throws filesystem_error on underlying OS API errors, constructed with from as the first argument, to as the second argument, and the OS error code as the error code argument. std:: bad_alloc may be thrown if memory allocation fails. The overload taking an error_code & parameter sets it to the OS API error code if an OS API call fails, and executes ec. clear ( ) if no errors occur. This overload has注释
这些函数最多涉及一次直接或间接调用
status(to)
(该调用既用于确定文件是否存在,也用于
copy_options::update_existing
选项的最近写入时间判断)。
当使用
copy_file
复制目录时会报错:此时应使用
copy
函数。
copy_file
遵循符号链接:如需处理符号链接请使用
copy_symlink
或带
copy_options::copy_symlinks
选项的
copy
函数。
示例
#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"); // 现在 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"
参见
|
指定复制操作的语义
(枚举) |
|
|
复制符号链接
(函数) |
|
|
复制文件或目录
(函数) |