std::filesystem::canonical, std::filesystem::weakly_canonical
来自 cppreference.cn
< cpp | filesystem
定义于头文件 <filesystem> |
||
path canonical( const std::filesystem::path& p ); |
(1) | (C++17 起) |
path canonical( const std::filesystem::path& p, std::error_code& ec ); |
(2) | (C++17 起) |
path weakly_canonical( const std::filesystem::path& p ); |
(3) | (C++17 起) |
path weakly_canonical( const std::filesystem::path& p, std::error_code& ec ); |
(4) | (C++17 起) |
1,2) 将路径 p 转换为规范绝对路径,即在其通用格式表示中没有点、点点元素或符号链接的绝对路径。 如果 p 不是绝对路径,则此函数的行为如同首先通过 std::filesystem::absolute(p) 使其成为绝对路径一样。 路径 p 必须存在。
3,4) 返回通过 operator/= 组合的路径,该路径来自调用
canonical()
的结果,其路径参数由 p 的前导元素(如果存在,由 status(p) 或 status(p, ec) 确定)和 p 的不存在元素组成。 结果路径为正规形式。内容 |
[编辑] 参数
p | - | 一个可以是绝对路径或相对路径的路径;对于 canonical ,它必须是已存在的路径 |
ec | - | 用于存储错误状态的错误码 |
[编辑] 返回值
1,2) 解析为与 std::filesystem::absolute(p) 相同文件的绝对路径。
3,4) 形式为 canonical(x)/y 的正规路径,其中 x 是由 p 中存在的最长前导元素序列组成的路径,而 y 是由 p 中剩余的尾随不存在元素组成的路径。
[编辑] 异常
任何未标记为 noexcept
的重载都可能在内存分配失败时抛出 std::bad_alloc。
[编辑] 注解
函数 canonical()
仿照 POSIX realpath
建模。
引入函数 weakly_canonical()
是为了简化 relative()
的操作语义。
[编辑] 示例
运行此代码
#include <filesystem> #include <iostream> int main() { /* set up sandbox directories: a └── b ├── c1 │ └── d <== current path └── c2 └── e */ auto old = std::filesystem::current_path(); auto tmp = std::filesystem::temp_directory_path(); std::filesystem::current_path(tmp); auto d1 = tmp / "a/b/c1/d"; auto d2 = tmp / "a/b/c2/e"; std::filesystem::create_directories(d1); std::filesystem::create_directories(d2); std::filesystem::current_path(d1); auto p1 = std::filesystem::path("../../c2/./e"); auto p2 = std::filesystem::path("../no-such-file"); std::cout << "Current path is " << std::filesystem::current_path() << '\n' << "Canonical path for " << p1 << " is " << std::filesystem::canonical(p1) << '\n' << "Weakly canonical path for " << p2 << " is " << std::filesystem::weakly_canonical(p2) << '\n'; try { [[maybe_unused]] auto x_x = std::filesystem::canonical(p2); // NOT REACHED } catch (const std::exception& ex) { std::cout << "Canonical path for " << p2 << " threw exception:\n" << ex.what() << '\n'; } // cleanup std::filesystem::current_path(old); const auto count = std::filesystem::remove_all(tmp / "a"); std::cout << "Deleted " << count << " files or directories.\n"; }
可能的输出
Current path is "/tmp/a/b/c1/d" Canonical path for "../../c2/./e" is "/tmp/a/b/c2/e" Weakly canonical path for "../no-such-file" is "/tmp/a/b/c1/no-such-file" Canonical path for "../no-such-file" threw exception: filesystem error: in canonical: No such file or directory [../no-such-file] [/tmp/a/b/c1/d] Deleted 6 files or directories.
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于之前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2956 | C++17 | canonical 具有虚假的 base 参数 |
已移除 |
[编辑] 参见
(C++17) |
表示路径 (类) |
(C++17) |
组成绝对路径 (函数) |
(C++17) |
组成相对路径 (函数) |