名稱空間
變體
操作

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

來自 cppreference.com
 
 
 
定義於標頭檔案 <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 的公開成員函式) [編輯]