How to split the path into separate lines?

This is a free question:
How to build a complete path line (safely) from separate lines?

So my question is how to split the path into separate lines in a cross-platform manner.

This solution using Boost.Filesystem is very elegant, and Boost must have implemented some splitPath () function. I could not find.

Note: Keep in mind that I can accomplish this task myself, but I'm more interested in a solution with a closed box.

+4
source share
3 answers

Indeed exists 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";
}

"/"
"tmp"
"foo.txt"

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

/
tmp
foo.txt

+7
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;
}
+5

If you don't have C ++ 11 auto or are writing cross-platform code, where boost :: filesystem :: path could 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());
}
+1
source

Source: https://habr.com/ru/post/1548334/


All Articles