c++stlfilesystemsstd

Why does std::filesystem::absolute resolve . and .. on Windows but not on POSIX platforms?


I'm using C++17's std::filesystem::absolute to convert relative paths to absolute ones. I noticed that on Windows (MSVC), this function seems to resolve . and .. components in the path, but on Linux (GCC/libstdc++), these components remain in the result.

For example, if my current directory is /home/user (or C:\Users on Windows):

std::filesystem::path rel = "foo/./bar/child/..";
auto abs = std::filesystem::absolute(rel);

On Windows, I get: C:\Users\foo\bar On Linux, I get: /home/user/foo/./bar/child/..

Is this platform-dependent behavior expected according to the C++ standard?


Solution

  • 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 <slash> characters".

    See fs.op.absolute, note 7:

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

    (And note the "might have".)