std::filesystem::canonical
From cppreference.com
< cpp | filesystem
| Defined in header
<filesystem>
|
||
| path canonical( const std::filesystem::path& p,
const std::filesystem::path& base = std::filesystem::current_path() ); |
(1) | (since C++17) |
| path canonical( const std::filesystem::path& p,
std::error_code& ec ); |
(2) | (since C++17) |
| path canonical( const std::filesystem::path& p,
const std::filesystem::path& base, |
(3) | (since C++17) |
Converts path p to a canonical absolute path, i.e. an absolute path that has no dot, dot-dot elements or symbolic links.
If p is not an absolute path, the function behaves as if it is first made absolute by absolute(p, base) or absolute(p) for (2)
The path p must exist.
Contents |
[edit] Parameters
| p | - | a path which may be absolute or relative to base, and which must be an existing path
|
| base | - | base path to be used in case p is relative
|
| ec | - | error code to store error status to |
[edit] Return value
An absolute path that resolves to the same file as absolute(p, base (or absolute(p) for (2)}}.
[edit] Exceptions
The overload that does not take a std::error_code& parameter throws filesystem_error on underlying OS API errors, constructed withp as the first argument, base as the second argument, and the OS error code as the error code argument. std::bad_alloc may be thrown if memory allocation fails. The overload taking a std::error_code& parameter sets it to the OS API error code if an OS API call fails, and executes ec.clear() if no errors occur. This overload has
noexcept specification:
noexcept
This function is modeled after the POSIX realpath.
[edit] Example
Run this code
#include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = fs::path("..") / ".." / "AppData"; std::cout << "Current path is " << fs::current_path() << '\n' << "Canonical path for " << p << " is " << canonical(p) << '\n'; }
Possible output:
Current path is "C:\Users\abcdef\AppData\Local\Temp" Canonical path for "..\..\AppData" is "C:/Users\abcdef\AppData"
[edit] See also
| (C++17)
|
represents a path (class) |
| (C++17)(C++17)
|
composes an absolute path converts a path to an absolute path replicating OS-specific behavior (function) |