c++boostboost-filesystemboost-foreach

Iterate over all files in a directory using BOOST_FOREACH


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.


Solution

  • 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
        } 
    }