Get absolute path with boost::filesystem::path
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).