8

I'm looking to achieve something like

if (basePath.contains(subPath)) {
    // subPath is a subPath of the basePath
}

I know I could achieve this by traversing the subPath's parents, checking for basePath on the way.

Is there an std method for this?


std::filesystem::path("/a/b/").contains("/a/b/c/d") == true

9
  • 2
    Have you looked up en.cppreference.com/w/cpp/filesystem ? Commented Jun 21, 2020 at 19:06
  • 3
    @Jesper Yes, I have Commented Jun 21, 2020 at 19:06
  • 1
    Look for the example recursive_directory_iterator
    – Ripi2
    Commented Jun 21, 2020 at 19:13
  • 1
    If you are looking for simple string comparisons, then something like subPath.compare(0, basePath.size(), basePath) == 0 might do the trick. Commented Jun 21, 2020 at 19:13
  • 1
    What would be the expected result of "/b/c".contains("/a/b/c/d")? "/b/c" is a substring of "/a/b/c/d", but while checking directories, /a/b/c/d has nothing to do with /b/c. (So, in my opinion, contains() should be more like startwith())
    – Dominique
    Commented Jun 21, 2020 at 19:38

3 Answers 3

4

Depending on your requirements (i.e. what you consider to be a subpath), you could try analysing the result of std::filesystem::relative(), for example:

bool is_subpath(const std::filesystem::path &path,
                const std::filesystem::path &base)
{
    auto rel = std::filesystem::relative(path, base);
    return !rel.empty() && rel.native()[0] != '.';
}

Note, this function returns false if the path relation cannot be determined, or if paths match.

1
  • Note: std::filesystem::relative resolves symbolic links while other solutions interpret the paths literally. (This was a plus for me, actually.) Commented Mar 5 at 18:41
4

https://en.cppreference.com/w/cpp/algorithm/mismatch can easily solve it in one line:

bool is_subpath(const fs::path& path, const fs::path& base) {
    const auto mismatch_pair = std::mismatch(path.begin(), path.end(), base.begin(), base.end());
    return mismatch_pair.second == base.end();
}

with the following tests (Catch2):

TEST_CASE("is_subpath", "[path]") {
    REQUIRE( is_subpath("a/b/c", "a/b") );
    REQUIRE_FALSE( is_subpath("a/b/c", "b") );
    REQUIRE_FALSE( is_subpath("a", "a/b/c") );
    REQUIRE_FALSE( is_subpath(test_root / "a", "a") );
    REQUIRE( is_subpath(test_root / "a", test_root / "a") );
}
0

You can iterate through items in both paths:

for (auto b = basePath.begin(), s = subPath.begin(); b != basePath.end(); ++b, ++s)
{
    if (s == subPath.end() || *s != *b)
    {
        return false;
    }
}
return true;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.