Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a file is contained by path with Boost Filesystem Library v3?

How can I determine if file is contained by path with boost filesystem v3.

I saw that there is a lesser or greater operator but this seems to be only lexical. The best way I saw was the following:

  • Take the two absolute paths of the file and the path
  • Remove the last part of the file and see if it equals the path (if it does it's contained)

Is there any better way to do this?

like image 499
David Feurle Avatar asked Mar 21 '13 06:03

David Feurle


People also ask

What library is filesystem in C++?

Filesystem library (since C++17) The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories. The filesystem library was originally developed as boost.

What is Boost filesystem?

The Boost Filesystem Library provides portable facilities to query and manipulate paths, files, and directories. The motivation for the library is the need to be able to perform portable script-like operations from within C++ programs.

Is boost filesystem header only?

Some boost libraries are header-only and some other need to be built (system, filesystem, graph, mpi, serialization, etc); several boost libraries can be configured to be either header-only or separately built.


1 Answers

The following function should determine whether a file name lies somewhere within the given directory, either as a direct child or in some subdirectory.

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

If you just want to check whether the directory is the immediate parent of the file, then use this instead:

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

You may also be interested in the discussion about what "the same" means with regard to operator== for paths.

like image 54
Rob Kennedy Avatar answered Oct 11 '22 12:10

Rob Kennedy