std::filesystem::path::append, std::filesystem::path::operator/=
來自 cppreference.com
< cpp | filesystem | path
path& operator/=( const path& p ); |
(1) | (C++17 起) |
template< class Source > path& operator/=( const Source& source ); |
(2) | (C++17 起) |
template< class Source > path& append( const Source& source ); |
(3) | (C++17 起) |
template< class InputIt > path& append( InputIt first, InputIt last ); |
(4) | (C++17 起) |
1) 若 p.is_absolute() || (p.has_root_name() && p.root_name() != root_name()),則如同透過 operator=(p),以 p 替換當前路徑然後完成。
* 否則,若 p.has_root_directory(),則從 *this 的通用格式路徑名移除任何根目錄和整個相對路徑。
* 否則,若 has_filename() || (!has_root_directory() && is_absolute()),則追加
path::preferred_separator
到 *this 的通用格式。 * 無論哪種方式,都接著追加 p 的原生格式路徑名(從其通用格式中省去任何根名)到 *this 的原生格式。
// Where "//host" is a root-name path("//host") / "foo" // the result is "//host/foo" (appends with separator) path("//host/") / "foo" // the result is also "//host/foo" (appends without separator) // On POSIX, path("foo") / "" // the result is "foo/" (appends) path("foo") / "/bar"; // the result is "/bar" (replaces) // On Windows, path("foo") / "C:/bar"; // the result is "C:/bar" (replaces) path("foo") / "C:"; // the result is "C:" (replaces) path("C:") / ""; // the result is "C:" (appends, without separator) path("C:foo") / "/bar"; // yields "C:/bar" (removes relative path, then appends) path("C:foo") / "C:bar"; // yields "C:foo/bar" (appends, omitting p's root-name)
2,3) 同 (1),但接受任何 std::basic_string、std::basic_string_view、空終止多字元字串,或指向空終止多字元序列的輸入迭代器。等價於 return operator/=(path(source));。
4) 同 (1),但接受任何指代多字元字串的迭代器對。等價於 return operator/=(path(first, last));。
(2) 與 (3) 僅若 Source
與 path
不是同一型別,且滿足下列條件之一,才參與過載決議:
-
Source
是 std::basic_string 或 std::basic_string_view 的特化,或 - std::iterator_traits<std::decay_t<Source>>::value_type 合法並指代一個可能帶 const 限定的編碼字元型別(char、 char8_t、 (C++20 起)char16_t、 char32_t 或 wchar_t)。
目錄 |
[編輯] 引數
p | - | - 要追加的路徑名 |
source | - | - std::basic_string、std::basic_string_view、空終止多字元字串,或指向表示路徑名(以可移植或原生格式)的空終止多字元序列的輸入迭代器 |
first, last | - | - 指定表示路徑名的多字元序列的一對遺留輸入迭代器 (LegacyInputIterator) |
型別要求 | ||
-InputIt 必須滿足 LegacyInputIterator 的要求。 | ||
-InputIt 的值型別必須是編碼字元型別之一(char、wchar_t、char16_t 及 char32_t)。 |
[編輯] 返回值
*this
[編輯] 異常
若記憶體分配失敗,可能丟擲 std::bad_alloc。
[編輯] 注意
這些函式有效地給出在 *this 是起始目錄的環境下,引數路徑 p 的含義的近似。
[編輯] 示例
輸出於 Windows 平臺產生。
執行此程式碼
#include <filesystem> #include <iostream> namespace fs = std::filesystem; int main() { fs::path p1 = "C:"; p1 /= "Users"; // does not insert a separator std::cout << "\"C:\" / \"Users\" == " << p1 << '\n'; p1 /= "batman"; // inserts fs::path::preferred_separator, '\' on Windows std::cout << "\"C:\" / \"Users\" / \"batman\" == " << p1 << '\n'; }
可能的輸出
"C:" / "Users" == "C:Users" "C:" / "Users" / "batman" == "C:Users\\batman"
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3244 | C++17 | 缺少 Source 不能是 path 的約束 |
已新增 |
[編輯] 參閱
連線兩個路徑而不引入目錄分隔符 (公開成員函式) | |
(C++17) |
用目錄分隔符連線兩個路徑 (函式) |