Pregunta

¿Cuál es la manera más limpia para buscar de forma recursiva para archivos usando C ++ y MFC?

EDIT: ¿Alguna de estas soluciones ofrecen la posibilidad de utilizar varios filtros a través de una sola pasada? Supongo que con CFileFind pude filtrar en *. * Y luego escribir código personalizado para filtrar aún más en diferentes tipos de archivos. ¿Tiene una función de oferta nada filtros múltiples (es decir. * .Exe, *. Dll)?

Edit2: Sólo se dio cuenta de un supuesto obvio que yo estaba haciendo eso hace que mi edición anterior válido. Si yo estoy tratando de hacer una búsqueda recursiva con CFileFind, tengo que usar *. * Como mi comodín, ya no serán emparejados de otra manera los subdirectorios y sin recursividad se llevará a cabo. Así filtrado en diferentes archivos-extensiones tendrá que tratarse por separado sin tener en cuenta.

¿Fue útil?

Solución

CFileFind .

Tome un vistazo a este ejemplo de 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();
}

Otros consejos

de aplicación del sistema de archivos Boost!

El ejemplo recursivo es aún en la página principal del sistema de archivos:

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

Sé que no es su pregunta, pero también es fácil de TO sin recursividad utilizando un 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();
  }
}
CString strNextFileName , strSaveLog= "C:\\mydir";
Find.FindFile(strSaveLog);
BOOL l = Find.FindNextFile();
if(!l)
    MessageBox("");
strNextFileName = Find.GetFileName();

no su trabajo. Find.FindNextFile () devolver falsos los que los archivos están presentes en el mismo directory``

scroll top