我有两个绝对文件系统路径(A 和 B),并且我想生成第三个文件系统路径来表示“A 相对于 B”。
使用案例:
- 管理播放列表的媒体播放器。
- 用户将文件添加到播放列表。
- 新文件路径已添加到播放列表相对于播放列表路径.
- 将来,整个音乐目录(包括播放列表)都会转移到其他地方。
- 所有路径仍然有效,因为它们是相对于播放列表的。
boost::filesystem
似乎有complete
解决relative ~ relative => absolute
,但没有什么可以反过来做(absolute ~ absolute => relative
).
我想用Boost路径来做到这一点。
使用 C++17 及其std::filesystem::relative https://en.cppreference.com/w/cpp/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
It uses std::filesystem::path::lexically_relative https://en.cppreference.com/w/cpp/filesystem/path/lexically_normal进行比较。
与纯词法函数的区别在于,std::filesystem::relative
解析符号链接并使用以下方法规范化两个路径std::filesystem::weakly_canonical https://en.cppreference.com/w/cpp/filesystem/canonical(这是为relative
) 比较之前。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)