3

What is the cleanest way to recursively search for files using C++ and MFC?

EDIT: Do any of these solutions offer the ability to use multiple filters through one pass? I guess with CFileFind I could filter on *.* and then write custom code to further filter into different file types. Does anything offer built-in multiple filters (ie. *.exe,*.dll)?

EDIT2: Just realized an obvious assumption that I was making that makes my previous EDIT invalid. If I am trying to do a recursive search with CFileFind, I have to use *.* as my wildcard because otherwise subdirectories won't be matched and no recursion will take place. So filtering on different file-extentions will have to be handled separately regardless.

jacobsee
  • 1,286
  • 4
  • 16
  • 30
  • 2
    The CFileFind class is just a thin wrapper over the FindFirstFile and FindNextFile Windows API functions. These don't give any provision for multiple wildcards. – Mark Ransom May 28 '09 at 16:06

5 Answers5

14

Using CFileFind.

Take a look at this example from MSDN:

void Recurse(LPCTSTR pstr)
{
   CFileFind finder;

   // build a string with wildcards
   CString strWildcard(pstr);
   strWildcard += _T("\\*.*");

   // start working for files
   BOOL bWorking = finder.FindFile(strWildcard);

   while (bWorking)
   {
      bWorking = finder.FindNextFile();

      // skip . and .. files; otherwise, we'd
      // recur infinitely!

      if (finder.IsDots())
         continue;

      // if it's a directory, recursively search it

      if (finder.IsDirectory())
      {
         CString str = finder.GetFilePath();
         cout << (LPCTSTR) str << endl;
         Recurse(str);
      }
   }

   finder.Close();
}
aJ.
  • 32,074
  • 21
  • 79
  • 124
4

Use Boost's Filesystem implementation!

The recursive example is even on the filesystem homepage:

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->leaf() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}
DevSolar
  • 59,831
  • 18
  • 119
  • 197
Kieveli
  • 10,548
  • 6
  • 48
  • 77
2

I know it is not your question, but it is also easy to to without recursion by using a CStringArray

void FindFiles(CString srcFolder)
{   
  CStringArray dirs;
  dirs.Add(srcFolder + "\\*.*");

  while(dirs.GetSize() > 0) {
     CString dir = dirs.GetAt(0);
     dirs.RemoveAt(0);

     CFileFind ff;
     BOOL good = ff.FindFile(dir);

     while(good) {
        good = ff.FindNextFile();
        if(!ff.IsDots()) {
          if(!ff.IsDirectory()) {
             //process file
          } else {
             //new directory (and not . or ..)
             dirs.InsertAt(0,nd + "\\*.*");
          }
        }
     }
     ff.Close();
  }
}
crashmstr
  • 26,648
  • 8
  • 59
  • 77
  • @ahoo oops. Doubt I can easily find the code I had for this, but `nd` would be from `ff.GetFileName()` or `ff.GetFilePath()`. So in each iteration, you add any found directories to the `dirs` list. [CFileFind](http://msdn.microsoft.com/en-us/library/f33e1618.aspx) – crashmstr Dec 22 '13 at 13:21
2

Check out the recls library - stands for recursive ls - which is a recursive search library that works on UNIX and Windows. It's a C library with adaptations to different language, including C++. From memory, you can use it something like the following:

using recls::search_sequence;


CString dir = "C:\\mydir";
CString patterns = "*.doc;abc*.xls";
CStringArray paths;
search_sequence files(dir, patterns, recls::RECURSIVE);

for(search_sequence::const_iterator b = files.begin(); b != files.end(); b++) {
    paths.Add((*b).c_str());
}

It'll find all .doc files, and all .xls files beginning with abc in C:\mydir or any of its subdirectories.

I haven't compiled this, but it should be pretty close to the mark.

DannyT
  • 12,669
  • 1
  • 16
  • 12
-1
CString strNextFileName , strSaveLog= "C:\\mydir";
Find.FindFile(strSaveLog);
BOOL l = Find.FindNextFile();
if(!l)
    MessageBox("");
strNextFileName = Find.GetFileName();

Its not working. Find.FindNextFile() returning false even the files are present in the same directory``

Chetan
  • 1
  • 1
    Maybe you need to add a wildcard to your path? strSaveLog= "C:\\mydir\\*.*". Also, don't ask a question in the place where an Answer should go! – jacobsee Apr 19 '15 at 16:29