Path Composition
C++ allows us to create a path in the form of a string. Let's find out how.
We'll cover the following...
We have two methods that allow to compose a path:
path::append()
- adds a path with a directory separator.path::concat()
- only adds the ‘string’ without any separator.
The functionality is also available with operators /
, /=
(append), +
and +=
(concat).
For example:
Press + to interact
#include <iostream>#include <filesystem>using namespace std;int main(){namespace fs = std::filesystem;fs::path p1("C:\\temp"); p1 /= "user";p1 /= "data";cout << p1 << '\n';fs::path p2("C:\\temp\\"); p2 += "user";p2 += "data";cout << p2 << '\n';}
However, appending a path has several rules that you have to be aware of.
For example, if the other path is absolute or the other path has a root-name, and the root-name is different from the current path root name. Then the append operation will replace this
.
auto resW = fs::path{"foo"} / "D:\"; // Windows
auto resP = fs::path{"foo"} / "/bar"; // POSIX
// resW is "D:\" now
// resP is now "/bar"
In the above case resW
and resP
will contain the value ...