Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a path into separate strings?

This is a complimentary question to:
How to build a full path string (safely) from separate strings?

So my question, how to split a path into separate strings in a cross platform manner.

This solution, using Boost.Filesystem is very elegant and Boost must have implemented some splitPath() function. I couldn't find any.

Note: bear in mind that I can do this task myself but I'm more interested in a closed box solution.

like image 783
idanshmu Avatar asked Jul 14 '14 10:07

idanshmu


3 Answers

Indeed, there is path_iterator. But if you want elegance:

#include <boost/filesystem.hpp>

int main() {
    for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
        std::cout << part << "\n";
}

Prints:

"/"
"tmp"
"foo.txt"

And

    for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
        std::cout << part.c_str() << "\n";

prints

/
tmp
foo.txt

No need to worry about the moving parts

like image 52
sehe Avatar answered Oct 19 '22 13:10

sehe


std::vector<std::string> SplitPath(const boost::filesystem::path &src) {
    std::vector<std::string> elements;
    for (const auto &p : src) {
        elements.emplace_back(p.filename());
    }
    return elements;
}
like image 5
ALittleDiff Avatar answered Oct 19 '22 11:10

ALittleDiff


If you don't have C++11 auto, or are writing cross-platform code where boost::filesystem::path might be std::wstring:

std::vector<boost::filesystem::path> elements;
for (boost::filesystem::path::iterator it(filename.begin()), it_end(filename.end()); it != it_end; ++it) 
{
    elements.push_back(it->filename());
}
like image 1
Jason Harrison Avatar answered Oct 19 '22 12:10

Jason Harrison