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 的原生格式路径名(从其通用格式省略任何 root-name)附到 *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)。
内容 |
[edit] 参数
p | - | 要附加的路径名 |
source | - | std::basic_string、std::basic_string_view、空终止多字符字符串,或指向空终止多字符序列的输入迭代器,它表示路径名(可移植格式或原生格式) |
first, last | - | LegacyInputIterator 的一对,指定表示路径名的多字符序列 |
类型要求 | ||
-InputIt 必须满足 LegacyInputIterator 的要求。 | ||
-InputIt 的值类型必须是编码字符类型之一(char、wchar_t、char16_t 和 char32_t)。 |
[edit] 返回值
*this
[edit] 异常
若内存分配失败,可能抛出 std::bad_alloc。
[edit] 注解
这些函数有效地产生实参路径 p 在 *this 为起始目录的环境中的意义的近似值。
[edit] 示例
输出在 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"
[edit] 缺陷报告
下列行为更改缺陷报告被追溯应用到先前发布的 C++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3244 | C++17 | Source 不能为 path 的约束缺失 |
已添加 |
[edit] 参见
连接两个路径,不引入目录分隔符 (公有成员函数) | |
(C++17) |
连接两个路径,带目录分隔符 (函数) |