The Boost C++ Libraries

Directory Iterators

Boost.Filesystem provides the iterator boost::filesystem::directory_iterator to iterate over files in a directory (see Example 35.18).

Example 35.18. Iterating over files in a directory
#include <boost/filesystem.hpp>
#include <iostream>

using namespace boost::filesystem;

int main()
  path p = current_path();
  directory_iterator it{p};
  while (it != directory_iterator{})
    std::cout << *it++ << '\n';

boost::filesystem::directory_iterator is initialized with a path to retrieve an iterator pointing to the beginning of a directory. To retrieve the end of a directory, the class must be instantiated with the default constructor.

Entries can be created or deleted while iterating without invalidating the iterator. However, whether changes become visible during the iteration is undefined. For example, the iterator might not point to newly created files. To ensure that all current entries are accessible, restart the iteration.

To recursively iterate over a directory and subdirectories, Boost.Filesystem provides the iterator boost::filesystem::recursive_directory_iterator.