Boost logo

Boost Users :

Subject: [Boost-users] questions about recursing a directory tree
From: Zsolt Ero (zsolt.ero_at_[hidden])
Date: 2010-11-23 05:35:21


I am just learning C++ and for a first project I would like to write a
program which goes recursively through a directory tree and returns
the newest and the oldest file date. I have been following the
documentation, but I couldn't really find a working example for a
recursive algorithm.

Shell I start by using this code from the v2 documentation?

----------------------------------
bool find_file( const path & dir_path, // in this directory,
                const std::string & file_name, // search for this name,
                path & path_found ) // placing path here if found
{
  if ( !exists( dir_path ) ) return false;
  directory_iterator end_itr; // default construction yields past-the-end
  for ( directory_iterator itr( dir_path );
        itr != end_itr;
        ++itr )
  {
    if ( is_directory(itr->status()) )
    {
      if ( find_file( itr->path(), file_name, path_found ) ) return true;
    }
    else if ( itr->path().filename() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}
-------------------------------

The other way I figured out is with recursive_directory_iterator:

------------------------------
#include "boost/filesystem.hpp"
#include <iostream>

namespace fs = boost::filesystem;
fs::recursive_directory_iterator end;
fs::recursive_directory_iterator dir("e:\\docs");

void main() {
        for ( ; dir != end; ++dir ) {
                std::cout << *dir << std::endl;
        }
}
-------------------------------

Is it safe to use recursive_directory_iterator on a really big
directory tree? I mean is it going to copy the whole tree into memory?
Does it walk through the whole directory tree the moment it's called,
or it only accesses the disk on a ++ operation one-by-one?

I still haven't looked into how to compare two files' date, but could
you give a hint about which function shell I use? Is it possible to
use just a simple < or > operation on file dates, or I need to write
manually if year1 > year2 and if month1 > month2, etc?

Thanks in advance,
Zsolt


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