Search code examples
c++boostpathsplitcross-platform

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.


Solution

  • 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