boost::filesystem get relative path

itun picture itun · Apr 16, 2012 · Viewed 22.2k times · Source

What methods of the boost::filesystem library can help me to get a path relative to another path?

I have a path /home/user1/Downloads/Books and a path /home/user1/. Now I want to get a path Downloads/Books.

Answer

milaniez picture milaniez · Jun 9, 2016

In new versions of boost (starting in 1.60), you can use boost::filesystem::relative. (See the documentation here.)

#include <boost/filesystem.hpp>
#include <iostream>
namespace fs = boost::filesystem;

int main()
{
    fs::path parentPath("/home/user1/");
    fs::path childPath("/home/user1/Downloads/Books");
    fs::path relativePath = fs::relative(childPath, parentPath);
    std::cout << relativePath << std::endl;
}