命名空间
变体
操作

std::filesystem::relative, std::filesystem::proximate

来自 cppreference.cn
 
 
 
定义于头文件 <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) 返回相对于 basep。在其他处理之前,解析符号链接并规范化 pbase。有效返回 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 将会相对于此路径被设为 relative/proximate
ec - 用于存储错误状态的错误码

[编辑] 返回值

1) 相对于 current_path() 的 relative p
2,3) 相对于 base 的 relative p
4) 相对于 current_path() 的 proximate p
5,6) 相对于 base 的 proximate p

[编辑] 异常

任何未标记为 noexcept 的重载都可能在内存分配失败时抛出 std::bad_alloc

2,5) 在底层操作系统 API 错误时,抛出 std::filesystem::filesystem_error,并使用 p 作为首个路径实参,base 作为第二个路径实参,以及操作系统错误码作为错误码实参来构造。
1,3,4,6) 若操作系统 API 调用失败,则将 std::error_code& 参数设置为操作系统 API 错误码,并且在没有错误发生时执行 ec.clear()

[编辑] 示例

#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)
组合一个绝对路径
(函数) [编辑]
组合一个规范路径
(函数) [编辑]
将路径转换为正常形式
将路径转换为相对形式
将路径转换为邻近形式
(std::filesystem::path 的公共成员函数) [编辑]