Boost logo

Boost Users :

From: Mikko Vainio (mivainio_at_[hidden])
Date: 2007-04-25 03:15:27


Jeff wrote:
> I am wondering if someone would possibly post a recursive function that prints
> out all files and sub-directories. I've never created a recursive function
> before and I'm having problems getting all files and directories to print.
>
> Thank You

Here's a short program that recursively prints out the directories and
files under (and including) the directory given as input.

#include <iostream>
#include <boost/filesystem/operations.hpp> // includes
boost/filesystem/path.hpp
#include <boost/filesystem/fstream.hpp>

using namespace std;
namespace fs = boost::filesystem;

void Recurse( fs::path & target );

int main(int argc, char *argv[])
{
        if( argc < 2 )
        {
                cerr << "Usage: " << argv[0] << " <path>" << endl;
                return 0;
        }
        fs::path rootpath( argv[1] );
        Recurse( rootpath );
        return 0;
}

void Recurse( fs::path & target )
{
        if( !fs::exists( target ) ) return;
        fs::directory_iterator end_itr; // default construction yields past-the-end
        if( fs::is_directory( target ) )
        {
                cout << target.string() << endl;
                for( fs::directory_iterator itr( target ); itr != end_itr; ++itr )
                        Recurse( *itr );
           }
        else // root of recursion
                cout << target.string() << endl;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net