首页 > 解决方案 > C++ 实验文件系统没有“相对”功能?

问题描述

标签: c++c++17

解决方案


You have to use third-party implementation (for ex. boost) or provide your own, something like (no complete solution - some extra edge cases need to be handled):

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;
}

推荐阅读