Domanda

Qual è il modo più pulito per la ricerca in modo ricorsivo i file in C ++ e MFC?

EDIT: Qualcuno di queste soluzioni offrono la possibilità di utilizzare più filtri attraverso un passaggio? Credo che con CFileFind Potrei filtrare *. * E quindi scrivere codice personalizzato per filtrare ulteriormente in diversi tipi di file. Non offre nulla di built-in filtri multipli (es. * .Exe, *. Dll)?

EDIT2: appena realizzato un presupposto ovvio che stavo facendo che rende la mia modifica precedente non valido. Se sto cercando di fare una ricerca ricorsiva con CFileFind, devo usare *. * Come il mio jolly perché altrimenti le sottodirectory non saranno abbinati e non ricorsione avrà luogo. Quindi, il filtraggio su diversi file-estensioni dovrà essere trattata separatamente a prescindere.

È stato utile?

Soluzione

CFileFind .

Date un'occhiata a questo esempio da 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();
}

Altri suggerimenti

implementazione del filesystem di Boost!

L'esempio ricorsiva è anche sulla home page filesystem:

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

So che non è la tua domanda, ma è anche facile da senza a ricorsione utilizzando 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();
  }
}

Controlla la recls biblioteca - sta per rec ursive ls - che è una libreria di ricerca ricorsiva che funziona su UNIX e Windows. Si tratta di una libreria C con adattamenti alla lingua diversa, tra cui C ++. Dalla memoria, si può utilizzare qualcosa di simile al seguente:

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

E 'accorgerete tutti i file .doc, .xls e tutti i file che iniziano con abc in C:. \ Mydir o una delle sue sottodirectory

Non ho compilato questo, ma dovrebbe essere abbastanza vicino al marchio.

CString strNextFileName , strSaveLog= "C:\\mydir";
Find.FindFile(strSaveLog);
BOOL l = Find.FindNextFile();
if(!l)
    MessageBox("");
strNextFileName = Find.GetFileName();

La sua non funziona. Find.FindNextFile () restituire falsi anche i file sono presenti nella stessa directory``

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top