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:
Is there any better way to do this?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With