std::filesystem::relative, std::filesystem::proximate
来自cppreference.com
< cpp | filesystem
<tbody>
</tbody>
| 在标头 <filesystem> 定义
|
||
path relative( const std::filesystem::path& p, std::error_code& ec ); |
(1) | (C++17 起) |
path relative( const std::filesystem::path& p, const std::filesystem::path& base = std::filesystem::current_path() ); |
(2) | (C++17 起) |
path relative( const std::filesystem::path& p, const std::filesystem::path& base, std::error_code& ec ); |
(3) | (C++17 起) |
path proximate( const std::filesystem::path& p, std::error_code& ec ); |
(4) | (C++17 起) |
path proximate( const std::filesystem::path& p, const std::filesystem::path& base = std::filesystem::current_path() ); |
(5) | (C++17 起) |
path proximate( const std::filesystem::path& p, const std::filesystem::path& base, std::error_code& ec ); |
(6) | (C++17 起) |
1) 返回
relative(p, current_path(), ec)2,3) 返回设为相对于
base 的 p。在其他处理前解析符号链接并正常化 p 与 base。相当于返回 std::filesystem::weakly_canonical(p).lexically_relative(std::filesystem::weakly_canonical(base)) 或 std::filesystem::weakly_canonical(p, ec).lexically_relative(std::filesystem::weakly_canonical(base, ec)),但错误码形式在首次错误出现时返回 path(),若有错误。4) 返回
proximate(p, current_path(), ec)。5,6) 相当于返回
std::filesystem::weakly_canonical(p).lexically_proximate(std::filesystem::weakly_canonical(base)) 或 std::filesystem::weakly_canonical(p, ec).lexically_proximate(std::filesystem::weakly_canonical(base, ec)),但错误码形式在首次错误出现时返回 path(),若有错误。参数
| p | - | 既存路径 |
| base | - | 基路径,p 将相对于它被设为相对/接近
|
| ec | - | 存储错误状态的错误码 |
返回值
1) 设为相对于
current_path() 的 p。2,3) 设为相对于
base 的 p。4) 设为接近
current_path() 的 p。5,6) 设为接近
base 的 p。异常
若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc 。
2,5) 抛出 std::filesystem::filesystem_error,构造时以
p 为第一路径实参,以 base 为第二路径实参,并以OS 错误码为错误码实参。示例
运行此代码
#include <filesystem>
#include <iostream>
void show(std::filesystem::path x, std::filesystem::path y)
{
std::cout << "x:\t\t " << x << "\ny:\t\t " << y << '\n'
<< "relative(x, y): "
<< std::filesystem::relative(x, y) << '\n'
<< "proximate(x, y): "
<< std::filesystem::proximate(x, y) << "\n\n";
}
int main()
{
show("/a/b/c", "/a/b");
show("/a/c", "/a/b");
show("c", "/a/b");
show("/a/b", "c");
}
可能的输出:
x: "/a/b/c"
y: "/a/b"
relative(x, y): "c"
proximate(x, y): "c"
x: "/a/c"
y: "/a/b"
relative(x, y): "../c"
proximate(x, y): "../c"
x: "c"
y: "/a/b"
relative(x, y): ""
proximate(x, y): "c"
x: "/a/b"
y: "c"
relative(x, y): ""
proximate(x, y): "/a/b"
参阅
(C++17) |
表示路径 (类) |
(C++17) |
组成一个绝对路径 (函数) |
(C++17) |
组成一个规范路径 (函数) |
| 转换路径到正常形式 转换路径到相对形式 转换路径到近似形式 ( std::filesystem::path 的公开成员函数)
|