Thalia
Thalia

Reputation: 14645

Create relative path using boost

I am trying to create relative paths using boost.

My initial plan was:

string base_directory;  // input
boost::filesystem::path base_path;
string other_directory;  // input
boost::filesystem::path other_path;
// assume base_path is absolute - did that already (using complete() 
// if path is relative, to root it in the current directory)  -> 
base_directory = base_path.string();

if (other_path.empty())
  other_directory = base_directory;
else
{
  other_path = boost::filesystem::path(other_directory);        
  if(!other_path.is_complete())
  {
    other_path = base_path / other_path;
    other_directory = other_path.string();          
  }
  if(!boost::filesystem::exists(boost::filesystem::path(other_path)))
  {
    boost::filesystem::create_directory(other_path);
  }
}

This works fine, if other_directory is absolute or just a name (or relative inner to base_directory).

But if I try to put ".." or "../other", I end up withe weird constructs, like "c:\test.." or "c:\test..\other"

How can I create relative paths properly, preferably using boost ? I tried to look in the documentation... without positive success.

I am using Windows (my preference for boost is that this should be multi-platform, and I am already dependent on it)

Edit: I have boost 1.47

Thank you for any suggestion.

Upvotes: 4

Views: 3620

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 64012

Boost filesystem does not know whether "C:\test" refers to a file or a directory, so it will not assume a trailing "\" is correct.

If you add that "\", you can use the function boost::filesystem::canonical() to simplify a path to remove . and .. elements.

other_path = boost::filesystem::path( other_directory + "\" );        
if(!other_path.is_complete())
{
  other_path = boost::filesystem::canonical( base_path / other_path );

Upvotes: 1

Related Questions