Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subtract one path from another?

So... I have a base path and a new path.New path contains in it base path. I need to see what is different in new path. Like we had /home/ and new path is /home/apple/one and I need to get from it apple/one. note - when I would create some path from (homePath/diffPath) I need to get that /home/apple/one again. How to do such thing with Boost FileSystem?

like image 533
Rella Avatar asked Apr 17 '11 16:04

Rella


1 Answers

Using stem() and parent_path() and walk backwards from the new path until we get back to base path, this works, but I am not sure if it is very safe. Be cautious, as the path "/home" and "/home/" are treated as different paths. The below only works if base path is /home (without trailing slash) and new path is guaranteed to be below 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;
}
like image 151
Oskar N. Avatar answered Sep 22 '22 03:09

Oskar N.