std::filesystem::path::append, std::filesystem::path::operator/=
来自 cppreference.cn
< 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) |
用目录分隔符连接两个路径 (函数) |