how to subtract one path from another?

╄→尐↘猪︶ㄣ 提交于 2020-01-14 10:43:29

问题


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?


回答1:


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



回答2:


Other solution, if you know that newpath really belongs to basepath, could be:

auto nit = newpath.begin();

for (auto bit = basepath.begin(); bit != basepath.end(); ++bit, ++nit)
    ;

fs::path = path(nit, newpath.end());


来源:https://stackoverflow.com/questions/5694700/how-to-subtract-one-path-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!