c++ - 如何使用 Boost Filesystem Library v3 确定文件是否包含在路径中?

标签 c++ boost boost-filesystem

如何确定文件是否包含在 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/

相关文章:

c++ - 模板函数特化与重载

c++ - 延长 boost::filtered 范围的生命周期

html - C++:如何递归/迭代搜索 HTML 文件(使用 Boost C++)?

c++ double to string 显示 float

c++ - 在 C++ 中是否有时不调用父类(super class)的构造函数?

c++ - 有没有办法获取有关 boost::flyweight 内部容器的信息?

c++ - 使用 C++ 的文件修改回调?

c++ - 有没有更简单的方法从 boost::filesystem::path 弹出目录?

c++ - 如何从一条路径中减去另一条路径?

c++ - ISO 文档 : based on Anonymous Unions 中的一点