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.
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
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;
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With