views:

505

answers:

2

I have a relative path (e.g. "foo/bar/baz/quux.xml") and I want to pop a directory off so that I will have the subdirectory + file (e.g. "bar/baz/quux.xml").

You can do this with path iterators, but I was hoping there was something I was missing from the documentation or something more elegant. Below is the code that I used.

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/exception.hpp>

#include <boost/assign.hpp>

boost::filesystem::path pop_directory(const boost::filesystem::path& path)
{
    list<string> parts;
    copy(path.begin(), path.end(), back_inserter(parts));

    if (parts.size() < 2)
    {
        return path;
    }
    else
    {
        boost::filesystem::path pathSub;
        for (list<string>::iterator it = ++parts.begin(); it != parts.end(); ++it)
        {
            pathSub /= *it;
        }
        return pathSub;
    }
}

int main(int argc, char* argv)
{
  list<string> test = boost::assign::list_of("foo/bar/baz/quux.xml")
  ("quux.xml")("foo/bar.xml")("./foo/bar.xml");
  for (list<string>::iterator i = test.begin(); i != test.end(); ++i)
  {
    boost::filesystem::path p(*i);
    cout << "Input: " << p.native_file_string() << endl;

    boost::filesystem::path p2(pop_directory(p));

    cout << "Subdir Path: " << p2.native_file_string() << endl;
  }
}

The output is:

Input: foo/bar/baz/quux.xml 
Subdir Path: bar/baz/quux.xml
Input: quux.xml
Subdir Path: quux.xml 
Input: foo/bar.xml 
Subdir Path: bar.xml
Input: ./foo/bar.xml 
Subdir Path: foo/bar.xml

What I was hoping for was something like:

boost::filesystem::path p1(someString);
boost::filesystem::path p2(p2.pop());

If you look at some test code on codepad.org, I have tried branch_path (returns "foo/bar/baz") and relative_path (returns "foo/bar/baz/quux.xml").

A: 
p2.parent_path() (or branch_path in older boost) ?
Marcus Lindblom
parent_path (or branch_path) just returns "foo/bar/baz". See the the test code that I added to the question.
chrish
+2  A: 

Here is something that a co-worker figured out just using string::find with boost::filesystem::slash. I like this that it doesn't require iterate over the entire path breaking it up, but also using the path's OS-independent definition of the path separation character. Thanks Bodgan!

boost::filesystem::path pop_front_directory(const boost::filesystem::path& path)
{
    string::size_type pos = path.string().find(boost::filesystem::slash<boost::filesystem::path>::value);
    if (pos == string::npos)
    {
        return path;
    }
    else
    {
        return boost::filesystem::path(path.string().substr(pos+1));
    }
}
chrish