rustyx
rustyx

Reputation: 85531

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:

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

Upvotes: 3

Views: 6437

Answers (3)

wangqr
wangqr

Reputation: 21

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)

Upvotes: 2

sehe
sehe

Reputation: 393789

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:

Upvotes: 3

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

boost::filesystem::path has a member function is_absolute(). So you can choose your operation (either concatenation or replacement) based on that.

path a = "/usr/home/";
path b = "/abc";
path c;

if (b.is_absolute())
    c = b;
else
    c = a / b;

There's also is_relative(), which does the opposite.

Upvotes: 5

Related Questions