Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the absolute path from std::filesystem::path c++

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

like image 542
Dev-il Avatar asked Jul 04 '20 11:07

Dev-il


People also ask

How do I get the full path of a file in C++?

If the image is in the current working directory of the program, you can use GetCurrentDirectory to get the absolute path to that directory.

What is filesystem path?

A filesystem is a structure for the computer to store the files and folders that make up the data of the operating system. Inside a filesystem, folders are referred to as directories. Folders that exist inside other folders are called subdirectories.

Which of the following command is using an absolute path?

To find the full absolute path of the current directory, use the pwd command.

What is Boost Filesystem?

The Boost Filesystem Library provides portable facilities to query and manipulate paths, files, and directories. The motivation for the library is the need to be able to perform portable script-like operations from within C++ programs.


Video Answer


2 Answers

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"
like image 181
f9c69e9781fa194211448473495534 Avatar answered Oct 18 '22 08:10

f9c69e9781fa194211448473495534


You can also use from this function.

 std::cout << std::filesystem::path("/root/home/../opt/.").lexically_normal()    << std::endl;
like image 20
Farhad Sarvari Avatar answered Oct 18 '22 07:10

Farhad Sarvari