命名空间
变体
操作

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 相对/近似
ec - 用于存储错误状态的错误代码

[编辑] 返回值

1) 相对于 current_path()p
2,3) 相对于 basep
4) 近似于 current_path()p
5,6) 近似于 basep

[编辑] 异常

任何未标记为 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 的公开成员函数) [编辑]