Directory Traversal : Traverse a directory tree

Given the root of a directory tree, return a list of files whose names match a given pattern.

Download directorytraversal.zip

Synopsis:

directorytraversal.cpp


directorytraversal.cpp

Synopsis
//WARNING UNTESTED!

#include <windows.h>
#include <iostream>
#include <string>
#include <list>
#include <stack>
using namespace std;

typedef list<string> FILELIST;

//-----------------------------------------------------
bool isMatch(const string& f)
  {
  return true; //to include the file
  }

//-----------------------------------------------------
void getFileList(string& aFileOrDirectory, FILELIST& filelist)
  {
  DWORD fattr = GetFileAttributes(aFileOrDirectory.c_str());
  if (fattr == 0xFFFFFFFF)
    {
    cout << "Could not find the file or directory '" << aFileOrDirectory << "'" << endl;
    return;
    }

  if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) //not a directory
    {
    filelist.push_back(aFileOrDirectory);
    return;
    }

  typedef std::stack<std::string> Paths;
  Paths dirs;
  WIN32_FIND_DATA fdata;

  dirs.push(aFileOrDirectory);
  while(!dirs.empty())
    {
    string dir = dirs.top();
    dirs.pop();
    string fspec = dir + "\\*.*";
    HANDLE hfile = FindFirstFile(fspec.c_str(), &fdata);

    if (hfile == INVALID_HANDLE_VALUE)
      continue;

    for (BOOL rc = TRUE; rc; rc = FindNextFile(hfile, &fdata))
      {
      string f(strlwr(fdata.cFileName));
      if (f == string(".") || f == string(".."))
        continue;

      if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
        dirs.push(string(dir + "\\" + f));
        continue;
        }

      if (isMatch(f))
        filelist.push_back(string(dir + "\\" + f));
      }

    FindClose(hfile);
    }
  }






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001,2002,2003,2004,2005,2006,2007