如何确定文件是否包含在Boost Filesystem Library v3的路径中?

时间:2013-03-21 06:59:01

标签: c++ boost boost-filesystem

如何确定文件是否包含在boost文件系统v3的路径中。

我看到有一个更小或更大的运算符,但这似乎只是词汇。 我看到的最好的方法如下:

  • 获取文件的两个绝对路径和路径
  • 删除文件的最后一部分,看它是否等于路径(如果它包含它)

有没有更好的方法呢?

2 个答案:

答案 0 :(得分:14)

以下函数应确定文件名是位于给定目录中的某个位置,可以是直接子目录还是某个子目录。

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;
}

您可能对operator==路径感兴趣the discussion about what "the same" means

答案 1 :(得分:1)

如果您只是想用词法检查一个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();
}

当然,如果您不希望对路径进行严格的词法比较,则可以对其中一个或两个参数调用lexically_normal()canonical()

相关问题