C++ Experimental filesystem has no "relative" function?

Viewed 493

I'm stuck with GCC7.1 for which I have to use #include <experimental/filesystem> instead of #include <filesystem>.

So I have namespace fs = std::experimental::filesystem; and then in the code I use fs::relative(p, base) which gives me error: ‘relative’ is not a member of ‘fs’.

It was working with normal C++17 filesystem, but doesn't seem to be present in experimental::filesystem. How can I use relative function with experimental::filesystem?

1 Answers

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