Namespaces
Variants

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

From cppreference.net
定义于头文件 <filesystem>
path relative ( const std:: filesystem :: path & p,
std:: error_code & ec ) ;
(1) (C++17 起)
(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 起)
(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) p 相对于 current_path ( ) 进行相对化处理。
2,3) p 相对于 base 进行相对化处理。
4) p 相对于 current_path ( ) 进行路径近似处理。
5,6) p 相对于 base 进行邻近对齐。

异常

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