[英]How to determine if a file is contained by path with Boost Filesystem Library v3?
如何使用 boost 文件系统 v3.0 确定文件是否包含在路径中?
我看到有一个较小或较大的运算符,但这似乎只是词法上的。 我看到的最好的方法如下:
有没有更好的方法来做到这一点?
以下函数应确定文件名是否位于给定目录中的某个位置,作为直接子目录或某个子目录。
bool path_contains_file(path dir, path file)
{
// If dir ends with "/" and isn't the root directory, then the final
// component returned by iterators will include "." and will interfere
// with the std::equal check below, so we strip it before proceeding.
if (dir.filename() == ".")
dir.remove_filename();
// We're also not interested in the file's name.
assert(file.has_filename());
file.remove_filename();
// If dir has more components than file, then file can't possibly
// reside in dir.
auto dir_len = std::distance(dir.begin(), dir.end());
auto file_len = std::distance(file.begin(), file.end());
if (dir_len > file_len)
return false;
// This stops checking when it reaches dir.end(), so it's OK if file
// has more directory components afterward. They won't be checked.
return std::equal(dir.begin(), dir.end(), file.begin());
}
如果您只想检查该目录是否是文件的直接父目录,请改用以下命令:
bool path_directly_contains_file(path dir, path file)
{
if (dir.filename() == ".")
dir.remove_filename();
assert(file.has_filename());
file.remove_filename();
return dir == file;
}
如果您只想在词法上检查一个path
是否是另一个path
的前缀,而不必担心.
, ..
或符号链接,你可以使用这个:
bool path_has_prefix(const path & path, const path & prefix)
{
auto pair = std::mismatch(path.begin(), path.end(), prefix.begin(), prefix.end());
return pair.second == prefix.end();
}
请注意,这里使用的std::mismatch
的四参数重载直到 C++14 才被添加。
当然,如果您想要的不仅仅是路径的严格词法比较,您可以对一个或两个参数调用lexically_normal()
或canonical()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.