如何确定文件是否包含在 boost 文件系统 v3 的路径中。
我看到有一个 lesser 或 greater 运算符,但这似乎只是词法上的。 我看到的最佳方式如下:
- 取文件和路径的两个绝对路径
- 删除文件的最后一部分并查看它是否等于路径(如果是则包含)
有没有更好的方法来做到这一点?
最佳答案
以下函数应确定文件名是否位于给定目录中的某个位置,作为直接子目录还是在某个子目录中。
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;
}
您可能还对 the discussion about what "the same" means 感兴趣关于路径的 operator==
。
关于c++ - 如何使用 Boost Filesystem Library v3 确定文件是否包含在路径中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15541263/