std::filesystem::path::lexically_normal, std::filesystem::path::lexically_relative, std::filesystem::path::lexically_proximate

path lexically_normal() const;
(1) (C++17 起)
path lexically_relative(const path& base) const;
(2) (C++17 起)
path lexically_proximate(const path& base) const;
(3) (C++17 起)
1) 返回以其通用格式转换成正常形式*this
2) 返回设为相对 base*this
  • 首先,若 root_name() != base.root_name() || is_absolute() != base.is_absolute() || (!has_root_directory() && base.has_root_directory()) ,则返回默认构造的路径。
  • 否则,首先确定 *thisbase 的首个不匹配元素,如同以 auto [a, b] = mismatch(begin(), end(), base.begin(), base.end()) ,然后
  • a == end()b == base.end() ,则返回 path(".")
  • 否则,若 [b, base.end())dot-dot 文件名元素数量大于既非 dot 亦非 dot-dot 的文件名元素数量,则返回默认构造的路径。
  • 否则返回由下列内容组成的对象
  • 默认构造的 path() 后随
  • [b, base.end()) 中既非 dot 亦非 dot-dot 的文件名元素数量减去该范围中 dot-dot 的元素数量,应用其结果次数的 operator/=(path("..")) ,后随
  • 对半开范围 [a, end()) 中的每个元素应用一次 operator/=
3)lexically_relative(base) 的值不是空路径,则返回它。否则返回 *this

目录

参数

(无)

返回值

1) 路径的正常形式
2) 路径的相对形式
3) 路径的接近形式

异常

(无)

注意

这些转换是纯字典的。它们不检查路径是否存在,不跟随符号链接,且完全不访问文件系统。关于 lexically_relativelexically_proximate 跟随符号链接的对应版本,见 relativeproximate

Windows 上返回路径拥有反斜杠(偏好分隔符)。

示例

#include <iostream>
#include <filesystem>
#include <cassert>
namespace fs = std::filesystem;
 
int main()
{
    assert(fs::path("foo/./bar/..").lexically_normal() == "foo/");
    assert(fs::path("foo/.///bar/../").lexically_normal() == "foo/");
 
    assert(path("/a/d").lexically_relative("/a/b/c") == "../../d");
    assert(path("/a/b/c").lexically_relative("/a/d") == "../b/c");
    assert(path("a/b/c").lexically_relative("a") == "b/c");
    assert(path("a/b/c").lexically_relative("a/b/c/x/y") == "../..");
    assert(path("a/b/c").lexically_relative("a/b/c") == ".");
    assert(path("a/b").lexically_relative("c/d") == "../../a/b");
}


参阅

组成一个相对路径
(函数)

版本历史

  • (当前 | 先前) 2017年5月1日 (一) 07:55Fruderica讨论 | 贡献. . (3,007字节) (+3,007). . (以“{{cpp/filesystem/path/title|lexically_normal|lexically_relative|lexically_proximate}} {{cpp/filesystem/path/navbar}} {{dcl begin}} {{dcl | since=c++17 | num=1 | 1= p...”为内容创建页面)