10

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

Dev-il
  • 157
  • 1
  • 8

2 Answers2

13

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"
7

You can also use from this function.

 std::cout << std::filesystem::path("/root/home/../opt/.").lexically_normal()    << std::endl;
Farhad Sarvari
  • 1,051
  • 7
  • 13
  • 6
    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. – Arthur Tacca Jul 04 '20 at 12:04