[英]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.我知道我可以通过遍历subPath
的父母,在途中检查basePath
来实现这一点。
Is there an std
method for this?有std
方法吗?
std::filesystem::path("/a/b/").contains("/a/b/c/d") == true
A std::filesystem::path
can be iterated over.可以迭代std::filesystem::path
。 Use std::search()
to check whether basePath
has a sequence of elements equal to subPath
:使用std::search()
检查basePath
是否具有等于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:根据您的要求(即您认为是子路径的内容),您可以尝试分析std::filesystem::relative()的结果,例如:
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.请注意,如果无法确定路径关系或路径匹配,则此 function 返回false
。
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: https://en.cppreference.com/w/cpp/algorithm/mismatch 一行就可以轻松解决:
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):通过以下测试(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") );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.