Iterate over all files in a directory using BOOST_FOREACH

Johan Råde picture Johan Råde · Jan 4, 2012 · Viewed 16.4k times · Source

Can you iterate over all files in a directory using boost::filesystem and BOOST_FOREACH? I tried

path dirPath = ...
int fileCount = 0;
BOOST_FOREACH(const path& filePath, dirPath)
    if(is_regular_file(filePath))
        ++fileCount;

This code compiles, runs, but does not produce the desired result.

Answer

nabulke picture nabulke · Jan 4, 2012

You can iterate over files in a directory using BOOST_FOREACH like this:

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp> 

namespace fs = boost::filesystem; 

fs::path targetDir("/tmp"); 

fs::directory_iterator it(targetDir), eod;

BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod))   
{ 
    if(fs::is_regular_file(p))
    {
        // do something with p
    } 
}