std::filesystem::copy_file
来自cppreference.com
< cpp | filesystem
<tbody>
</tbody>
| 在标头 <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, std::error_code& ec ); |
(2) | (C++17 起) |
bool copy_file( const std::filesystem::path& from, const std::filesystem::path& to, std::filesystem::copy_options options ); |
(3) | (C++17 起) |
bool copy_file( const std::filesystem::path& from, const std::filesystem::path& to, std::filesystem::copy_options options, std::error_code& ec ); |
(4) | (C++17 起) |
1,2) 默认,等价于以
copy_options::none 为 options 调用 (3,4)。 3,4) 从
from 到 to 复制单个文件,使用 options 所指示的复制选项。若 options 中存在任一 copy_options 选项组中多于一个的选项,则行为未定义(即使在无关乎 std::filesystem::copy_file 的组中)。
- 若 std::filesystem::is_regular_file(因为源文件不存在或它不是常规文件),则报告错误。
- 否则,若目标文件不存在,则
- 复制
from所解析到的文件的内容及属性到to所解析到者(跟随符号链接)
- 复制
- 否则,若目标文件已存在……
- 若下列之一为真则报告错误:
to与from相同,以 std::filesystem::equivalent 确定;to不是常规文件,以 std::filesystem::is_regular_file 确定;options中未设置任何 std::filesystem::copy_file 控制选项。
- 否则,若
copy_options::skip_existing设置于options,则不做任何事 - 否则,若
copy_options::overwrite_existing设置于options,则复制from所解析到的文件的内容及属性到to所解析到的文件。 - 否则,若
copy_options::update_existing设置于options,则仅若from按 std::filesystem::last_write_time 定义比to更新才复制文件。
当发生错误时,不抛出重载返回 false。
参数
| from | - | 源文件的路径 |
| to | - | 目标文件的路径 |
| ec | - | 不抛出重载中报告错误的输出形参 |
返回值
若文件被复制则返回 true,否则返回 false。
异常
若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc 。
1,3) 抛出 std::filesystem::filesystem_error,构造时以
from 为第一路径实参,以 to 为第二路径实参,并以OS 错误码为错误码实参。注解
函数最多引入一次对 std::filesystem::status 的直接或间接调用(均用于确定文件是否存在,及对于 filesystem::copy_options::update_existing 选项,确定其最后写入时间)。
当 std::filesystem::copy_file 被用于复制目录时报告错误:用 std::filesystem::copy 复制它们。
std::filesystem::copy_file 跟随符号链接:为其调用 std::filesystem::copy_symlink 或以 filesystem::copy_options::copy_symlinks 调用 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");
// 现在 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++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3014 | C++17 | error_code 重载被标记为 noexcept 但能分配内存
|
移除 noexcept |
参阅
(C++17) |
指定复制操作的语义 (枚举) |
(C++17) |
复制一个符号链接 (函数) |
(C++17) |
复制文件或目录 (函数) |