我坚持使用GCC7.1,必须使用#include <experimental/filesystem>
而不是#include <filesystem>
。
所以我有namespace fs = std::experimental::filesystem;
,然后在代码中我使用fs::relative(p, base)
,这给了我error: ‘relative’ is not a member of ‘fs’
。
它可以在正常的C++ 17文件系统中使用,但在实验性::文件系统中似乎不存在。 如何将相对功能与experimental::filesystem一起使用?
最佳答案
您必须使用第三方实现(例如,增强功能)或提供自己的功能,例如(没有完整的解决方案-需要处理一些额外的情况):
path relative(path p, path base)
{
// 1. convert p and base to absolute paths
p = fs::absolute(p);
base = fs::absolute(base);
// 2. find first mismatch and shared root path
auto mismatched = std::mismatch(p.begin(), p.end(), base.begin(), base.end());
// 3. if no mismatch return "."
if (mismatched.first == p.end() && mismatched.second == base.end())
return ".";
auto it_p = mismatched.first;
auto it_base = mismatched.second;
path ret;
// 4. iterate abase to the shared root and append "../"
for (; it_base != base.end(); ++it_base) ret /= "..";
// 5. iterate from the shared root to the p and append its parts
for (; it_p != p.end(); ++it_p) ret /= *it_p;
return ret;
}
关于c++ - C++实验文件系统没有 “relative”函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63899489/