Get the absolute path from std::filesystem::path c++
Asked Answered
J

2

11

I have this piece of code

auto path = std::filesystem::path("/root/home/../opt/.");

I had tried std::filesystem::absolute() but then realized it is for something else than the reasult I want

My question is how can i convert that relative path to the absolute path so that the reasult will be "/root/opt/".

I am using c++17 on Debian g++-9

Jedjedd answered 4/7, 2020 at 11:42 Comment(1)
You want the canonical path (link).Trautman
T
16

Use std::filesystem::canonical to turn the path into an absolute path with all .. removed (reference):

auto path = std::filesystem::canonical("/root/home/../opt/.");

Gives you:

"/root/opt"
Trautman answered 4/7, 2020 at 11:52 Comment(0)
P
7

You can also use from this function.

 std::cout << std::filesystem::path("/root/home/../opt/.").lexically_normal()    << std::endl;
Putup answered 4/7, 2020 at 12:0 Comment(1)
It's worth noting: unlike the other answer (canonical), the lexically_normal method will not attempt to resolve symlinks, and in fact won't do any file system operations at all. It's just a string manipulation method, hence the name. Depending on the situation, this may or may not be what you want.Maroc

© 2022 - 2024 — McMap. All rights reserved.