Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path with boost::filesystem::path

People also ask

What is boost :: filesystem :: path?

boost::filesystem::path is the central class in Boost. Filesystem for representing and processing paths. Definitions can be found in the namespace boost::filesystem and in the header file boost/filesystem. hpp . Paths can be built by passing a string to the constructor of boost::filesystem::path (see Example 35.1).

How do you find the absolute path?

To find the full absolute path of the current directory, use the pwd command. Once you've determined the path to the current directory, the absolute path to the file is the path plus the name of the file.

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 absolute path in CMD?

An absolute path contains the full set of directories from the root of the file system up to your target file or directory. On Windows, an absolute path starts with a drive like C:\ . You can cd to an absolute path from anywhere on the filesystem. This is an example absolute path: C:\Users\jesstess\projects.


You say you want an absolute path, but your example shows that you already have an absolute path. The process of removing the .. components of a path is known as canonicalization. For that, you should call canonical. It happens to also perform the task of absolute, so you don't need to call absolute or make_absolute first. The make_absolute function requires a base path; you can pass it current_path() if you don't have anything better.


Update, since this still appears to be Google's top hit concerning absolute paths:

As of Boost 1.57, some of the previously suggested functions have since been removed.

The solution that worked for me was

boost::filesystem::path canonicalPath = boost::filesystem::canonical(previousPath, relativeTo);

(using the free-standing method canonical(), defined in boost/filesystem/operations.hpp, which is automatically included via boost/filesystem.hpp)

Important: calling canonical on a path that does not exist (e.g., you want to create a file) will throw an exception. In that case, your next best bet is probably boost::filesystem::absolute(). It will also work for non-existing paths, but won't get rid of dots in the middle of the path (as in a/b/c/../../d.txt). Note: Make sure relativeTo refers to a directory, calling parent_path() on paths referring to files (e.g. the opened file that contained a directory or file path relative to itself).


The documentation shows that the make_absolute has an optional second parameter that defaults to your current path:

path absolute(const path& p, const path& base=current_path());

Try it without the second parameter and see if it returns the results you're looking for.