Walking a folder structure in most languages is typically achieved using a recursive function or loop of some kind (although this behaviour may be wrapped and hidden from the programmer) - for C++ this is not any different. However the walking isn't the problem, rather writing a platform generic (Unix/Linux/Windows) version has been a little tricky due to C++ having no standardised support for folder/directory handling across different platforms (of course file handling is standardised.).
Boost makes this simple using it's
filesystem library iterators and a very simple loop construct of your choice.
Example
This example shows a recursive walk of a folder structure printing the full path of all folders and files found.
#include <boost/filesystem.hpp>
#include <iostream>
void main()
{
boost::filesystem::path path = boost::filesystem::current_path();
boost::filesystem::recursive_directory_iterator itr(path);
while (itr != boost::filesystem::recursive_directory_iterator())
{
std::cout << itr->path().string() << std::endl;
++itr;
}
}
- Firstly we assume you have built the Boost filesystem library and it and it's header are appropriately defined in your project e.g. link to the library and include the header file.
- Next you create the iterator recursive_directory_iterator. We have loaded our iterator example with the current working directory.
- Finally you loop until you run out of iterators.
References
http://www.boost.org/