C ++检查路径是否在给定目录之外 [英] C++ check if path is outside a given directory
本文介绍了C ++检查路径是否在给定目录之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检查给定路径A是否在另一路径B之外的最简单方法是什么?即:确定 foo/../../bar/
是否在 foo/
之外.
What is the simplest way to check if a given path A is outside another path B?
I.e.: determine whether foo/../../bar/
is outside foo/
.
推荐答案
类似的东西应该可以工作.另外请注意,这两个路径都应该存在.
Something like this should work. Also note that both paths should exist.
#include <filesystem>
#include <algorithm>
#include <iterator>
#include <cassert>
bool isSafePath(const std::filesystem::path &root, const std::filesystem::path &child) {
auto const normRoot = std::filesystem::canonical(root);
auto const normChild = std::filesystem::canonical(child);
auto itr = std::search(normChild.begin(), normChild.end(),
normRoot.begin(), normRoot.end());
return itr == normChild.begin();
}
int main(int argc, char **argv)
{
assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg/index.html"));
assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg"));
assert(isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../apps/CMakeLists.txt"));
assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../../../../../etc/shadow"));
assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../CMakeLists.txt"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../../../../../../../etc/fstab"));
return 0;
}
这篇关于C ++检查路径是否在给定目录之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文