std::filesystem::canonical, std::filesystem::weakly_canonical
来自cppreference.com
< cpp | filesystem
| 在标头 <filesystem> 定义
|
||
| |
(1) | (C++17 起) |
| |
(2) | (C++17 起) |
| |
(3) | (C++17 起) |
| |
(4) | (C++17 起) |
1,2) 转换路径
p 为规范绝对路径,即在其通用格式表示中没有点、点点元素或符号链接的绝对路径。若 p 不是绝对路径,则该函数表现为首先用 absolute(p) 将它转换为绝对。路径 p 必须存在。3,4) 返回由调用
canonical() 的结果以 operator/= 组合成的路径,该调用的路径实参由 p 中存在的前导元素(如以 status(p) 或 status(p, ec) 确定),若有这些,后随 p 的不存在元素组成。产生的路径为正常形式。参数
| p | - | 可以为绝对或相对的路径;对于 canonical 必须是存在的路径
|
| ec | - | 存储错误状态的错误码 |
返回值
1,2) 解析到与
std::filesystem::absolute(p) 或 std::filesystem::absolute(p, ec) 为相同文件的绝对路径。3,4)
canonical(x)/y 形式的正常路径,其中 x 是由 p 中存在的元素的最长前导序列组成的路径,而 y 是由 p 中剩余尾随的不存在元素组成的路径。异常
若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc 。
1,3) 抛出 std::filesystem::filesystem_error,构造时以
p 为第一路径实参并以OS 错误码为错误码实参。注解
函数 canonical() 模仿 POSIX realpath。
引入函数 weakly_canonical() 以简化 relative() 的操作语义。
示例
Run this code
#include <filesystem>
#include <iostream>
int main()
{
/* 设立沙盒目录:
a
└── b
├── c1
│ └── d <== 当前路径
└── 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 << "当前路径为 "
<< std::filesystem::current_path() << '\n'
<< p1 << " 的规范路径为 "
<< std::filesystem::canonical(p1) << '\n'
<< p2 << " 的弱规范路径为 "
<< std::filesystem::weakly_canonical(p2) << '\n';
try
{
[[maybe_unused]] auto x_x = std::filesystem::canonical(p2);
// 不会抵达此处
}
catch (const std::exception& ex)
{
std::cout << p2 << " 的规范路径抛出了异常:\n"
<< ex.what() << '\n';
}
// 清理
std::filesystem::current_path(old);
const auto count = std::filesystem::remove_all(tmp / "a");
std::cout << "删除了 " << count << " 个文件或目录。\n";
}
可能的输出:
当前路径为 "/tmp/a/b/c1/d"
"../../c2/./e" 的规范路径为 "/tmp/a/b/c2/e"
"../no-such-file" 的弱规范路径为 "/tmp/a/b/c1/no-such-file"
"../no-such-file" 的规范路径抛出了异常:
filesystem error: in canonical: No such file or directory [../no-such-file] [/tmp/a/b/c1/d]
删除了 6 个文件或目录。
参阅
(C++17) |
表示路径 (类) |
(C++17) |
组成一个绝对路径 (函数) |
(C++17) |
组成一个相对路径 (函数) |