简体   繁体   中英

Check if path contains another in C++

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

A std::filesystem::path can be iterated over. Use std::search() to check whether basePath has a sequence of elements equal to subPath :

#include <algorithm>

if (std::search(basePath.begin(), basePath.end(), subPath.begin(), subpath.end()) != basePath.end()) {
   // subPath is a subPath of the basePath
}

Depending on your requirements (ie 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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM