C++: How do I ignore the first directory path when comparing paths in boost::filesystem?
The boost::filesystem::recursive_directory_iterator
has a path()
property that you can query. You can then use the following decomposition methods available for boost::filesystem::path
to manually build the path to compare:
path root_path() const;
path root_name() const; // returns 0 or 1 element path
path root_directory() const; // returns 0 or 1 element path
path relative_path() const;
path parent_path() const;
path filename() const; // returns 0 or 1 element path
path stem() const; // returns 0 or 1 element path
path extension() const; // returns 0 or 1 element path
For example you can rollout a version of stripping the root as follows:
#include <iostream>
#include <boost/filesystem.hpp>
boost::filesystem::path strip_root(const boost::filesystem::path& p) {
const boost::filesystem::path& parent_path = p.parent_path();
if (parent_path.empty() || parent_path.string() == "/")
return boost::filesystem::path();
else
return strip_root(parent_path) / p.filename();
}
int main() {
std::cout << strip_root("/a") << std::endl;
std::cout << strip_root("/a/b") << std::endl;
std::cout << strip_root("/a/b/c") << std::endl;
std::cout << strip_root("/a/b.dir/c.ext") << std::endl;
}
// Output:
""
"b"
"b/c"
"b.dir/c.ext"