Search code examples
c++boostboost-filesystem

How to combine two boost::filesystem::path's?


I need to combine an absolute path A with path B, given that B may be relative as well as absolute, preferably using boost::filesystem.

In other words, I want to have:

  • /usr/home/ + abc = /usr/home/abc
  • /usr/home/ + ../abc = /usr/home/../abc (or, even better /usr/abc - this is not my question)
  • /usr/home/ + /abc = /abc

The first two are easy with the / operator but I can't get the third one to work.

I tried:

std::cout << boost::filesystem::path("/usr/home/") / "/abc";

Prints /usr/home//abc.

std::cout << boost::filesystem::path("/usr/home/") + "/abc";

Still prints /usr/home//abc.

Of course I can "see" when path B is absolute by looking at it and just use that, but I don't want to hardcode the check for the leading / because on Windows it can be different (e.g. C:\\ or \\).


Solution

  • If you are looking to make a relative path absolute with respect to some directory (often the current working directory), there is a function to do this: