c++ - 从两个绝对路径获取相对路径

标签 c++ boost boost-filesystem

我有两个绝对文件系统路径(A 和 B),我想生成第三个文件系统路径,表示“A 相对于 B”。

用例:

  • 管理播放列表的媒体播放器。
  • 用户将文件添加到播放列表。
  • 添加到播放列表的新文件路径相对于播放列表路径
  • 将来,整个音乐目录(包括播放列表)都会移到其他地方。
  • 所有路径仍然有效,因为它们与播放列表相关。

boost::filesystem 似乎有 complete 来解析 relative ~ relative => absolute,但没有任何反作用(absolute ~ absolute => relative).

我想用 Boost 路径来做。

最佳答案

使用 C++17 及其 std::filesystem::relative ,它是从 boost 演变而来的,这是不费吹灰之力的:

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main()
{
    const fs::path base("/is/the/speed/of/light/absolute");
    const fs::path p("/is/the/speed/of/light/absolute/or/is/it/relative/to/the/observer");
    const fs::path p2("/little/light/races/in/orbit/of/a/rogue/planet");
    std::cout << "Base is base: " << fs::relative(p, base).generic_string() << '\n'
              << "Base is deeper: " << fs::relative(base, p).generic_string() << '\n'
              << "Base is orthogonal: " << fs::relative(p2, base).generic_string();
    // Omitting exception handling/error code usage for simplicity.
}

输出(第二个参数是基数)

Base is base: or/is/it/relative/to/the/observer
Base is deeper: ../../../../../../..
Base is orthogonal: ../../../../../../little/light/races/in/orbit/of/a/rogue/planet

它使用 std::filesystem::path::lexically_relative进行比较。 与纯词法函数的区别在于,std::filesystem::relative 解析符号链接(symbolic link)并使用规范化两个路径 std::filesystem::weakly_canonical (在比较之前为 relative 引入)。

关于c++ - 从两个绝对路径获取相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772992/

相关文章:

C++ 4.8 运行时堆损坏

c++ - 混合 Qt 和 Boost

c++ - std::transform with lambda: 跳过一些项目

python - 使用 Boost::Python 进行高阶编程

c++ - Boost::filesystem::is_symlink() 不起作用

c++ - 引用计数

c++ - 匹配语料库中的多个字符串

c++ - 使用 CMake 查找使用 CLang 编译的 Boost

c++ - 如何在不打开文件的情况下测试文件是否被锁定和/或只读?

c++ - 移植access(2)Linux系统调用boost::filesystem