How to subtract one path from another?

So ... I have a base path and a new path. The new path contains the base path in it. I need to see that in a new way. For example, we had / home / and the new path / home / apple / one, and I need to get apple / one from it. note - when I create some path from (homePath / diffPath), I need to get this / home / apple / one again. How to do it with Boost FileSystem?

+3
c ++ boost boost-filesystem
Apr 17 '11 at 16:22
source share
2 answers

Using the stem () and parent_path () functions and go back from the new path until we get back to the base path, this works, but I'm not sure if this is very safe. Be careful because the paths "/ home" and "/ home /" are treated as different paths. The following only works if the base path is / home (without a trailing slash) and the new path is guaranteed to be below the base path in the directory tree.

#include <iostream> #include <boost/filesystem.hpp> int main(void) { namespace fs = boost::filesystem; fs::path basepath("/home"); fs::path newpath("/home/apple/one"); fs::path diffpath; fs::path tmppath = newpath; while(tmppath != basepath) { diffpath = tmppath.stem() / diffpath; tmppath = tmppath.parent_path(); } std::cout << "basepath: " << basepath << std::endl; std::cout << "newpath: " << newpath << std::endl; std::cout << "diffpath: " << diffpath << std::endl; std::cout << "basepath/diffpath: " << basepath/diffpath << std::endl; return 0; } 
+8
Apr 18 2018-11-11T00:
source share

Another solution, if you know that newpath really belongs to basepath , might be:

 auto nit = newpath.begin(); for (auto bit = basepath.begin(); bit != basepath.end(); ++bit, ++nit) ; fs::path = path(nit, newpath.end()); 
0
Jan 10 '16 at 19:40
source share



All Articles