Question Details

No question body available.

Tags

c++ stl filesystems std

Answers (3)

Accepted Answer Available
Accepted Answer
April 29, 2025 Score: 2 Rep: 67,085 Quality: High Completeness: 70%

Yes, it's platform-dependent (it is more or less impossible to present a unified filesystem interface for all platforms) and POSIX defines an absolute path as "[a] pathname beginning with a single or more than two characters".

See fs.op.absolute, note 7:

For POSIX-based operating systems, absolute(p) is simply currentpath()/p. For Windows-based operating systems, absolute might have the same semantics as GetFullPathNameW.

(And note the "might have".)

April 29, 2025 Score: 7 Rep: 40,551 Quality: Medium Completeness: 70%

Most probably as a solution you should use function lexicallynormal() which will strip any relative parts of the path from absolute path.

#include "catch2/catchall.hpp"

#include

namespace fs = std::filesystem;

TESTCASE("filesystem") { auto [relative, absolute] = GENERATE(table({ { ".", "/app/" }, { "./foo/../bar", "/app/bar" }, { "./foo/././bar", "/app/foo/bar" }, })); CAPTURE(relative, absolute); // CHECK(fs::absolute(relative) == absolute); CHECK(fs::absolute(relative).lexically_normal() == absolute); }

https://godbolt.org/z/nWEhxfETK

April 30, 2025 Score: 1 Rep: 18,766 Quality: Medium Completeness: 100%
  • A path leads you to a destination (a file).

  • A relative path leads you to a destination starting from your current location.

  • An absolute path leads you to a destination starting from a fixed location.

  • A normalized path leads you to a destination without needless backtracking (x/../) or pausing (/./ or ////) and with all slashes pointing the "right" way (for your platform).

  • A canonical path avoids backtracking, pauses, and also shortcuts (symbolic links).


Normalization is orthogonal to relative/absolute. The former deals with how the path proceeds, while the latter deal with how the path starts. Both relative and absolute paths can be normalized, and neither requires it. Note, though, that to make things more complicated, std::filesystem::canonical returns a canonical absolute path, even though "absolute" is not in the function name. Special case, not the norm.

std::filesystem::absolute promises an absolute path to the specified destination, nothing more. This makes sense, given the principle that you do not pay for what you do not need. If you need the result normalized, you can always invoke lexicallynormal() on the returned value. If you are using the same parameter multiple times (from different starting directories), it might be better to normalize the parameter in advance, although there is no guarantee that the leading .. will be resolved by absolute().