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

Viewed 5123

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 \\).

3 Answers

You can also use the C++17 std::filesystem::path. Its operator/ does exactly what you need.

// where "//host" is a root-name
path("//host")  / "foo" // the result is      "//host/foo" (appends with separator)
path("//host/") / "foo" // the result is also "//host/foo" (appends without separator)

// On POSIX,
path("foo") / ""      // the result is "foo/" (appends)
path("foo") / "/bar"; // the result is "/bar" (replaces)

// On Windows,
path("foo") / "C:/bar";  // the result is "C:/bar" (replaces)
path("foo") / "C:";      // the result is "C:"     (replaces)
path("C:") / "";         // the result is "C:"     (appends, without separator)
path("C:foo") / "/bar";  // yields "C:/bar"        (removes relative path, then appends)
path("C:foo") / "C:bar"; // yields "C:foo/bar"     (appends, omitting p's root-name)
Related