CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Windows SDK File System: How to search for files in a directory and subdirectories?

    Q: How to search for files in a directory and subdirectories?

    A:

    Code:
    #include <string>
    #include <vector>
    #include <iostream>
    
    #include <windows.h>
    #include <conio.h>
    
    
    
    int SearchDirectory(std::vector<std::string> &refvecFiles,
                        const std::string        &refcstrRootDirectory,
                        const std::string        &refcstrExtension,
                        bool                     bSearchSubdirectories = true)
    {
      std::string     strFilePath;             // Filepath
      std::string     strPattern;              // Pattern
      std::string     strExtension;            // Extension
      HANDLE          hFile;                   // Handle to file
      WIN32_FIND_DATA FileInformation;         // File information
    
    
      strPattern = refcstrRootDirectory + "\\*.*";
    
      hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
      if(hFile != INVALID_HANDLE_VALUE)
      {
        do
        {
          if(FileInformation.cFileName[0] != '.')
          {
            strFilePath.erase();
            strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
    
            if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
              if(bSearchSubdirectories)
              {
                // Search subdirectory
                int iRC = SearchDirectory(refvecFiles,
                                          strFilePath,
                                          refcstrExtension,
                                          bSearchSubdirectories);
                if(iRC)
                  return iRC;
              }
            }
            else
            {
              // Check extension
              strExtension = FileInformation.cFileName;
              strExtension = strExtension.substr(strExtension.rfind(".") + 1);
    
              if(strExtension == refcstrExtension)
              {
                // Save filename
                refvecFiles.push_back(strFilePath);
              }
            }
          }
        } while(::FindNextFile(hFile, &FileInformation) == TRUE);
    
        // Close handle
        ::FindClose(hFile);
    
        DWORD dwError = ::GetLastError();
        if(dwError != ERROR_NO_MORE_FILES)
          return dwError;
      }
    
      return 0;
    }
    
    
    int main()
    {
      int                      iRC         = 0;
      std::vector<std::string> vecAviFiles;
      std::vector<std::string> vecTxtFiles;
    
    
      // Search 'c:' for '.avi' files including subdirectories
      iRC = SearchDirectory(vecAviFiles, "c:", "avi");
      if(iRC)
      {
        std::cout << "Error " << iRC << std::endl;
        return -1;
      }
    
      // Print results
      for(std::vector<std::string>::iterator iterAvi = vecAviFiles.begin();
          iterAvi != vecAviFiles.end();
          ++iterAvi)
        std::cout << *iterAvi << std::endl;
    
      // Search 'c:\textfiles' for '.txt' files excluding subdirectories
      iRC = SearchDirectory(vecTxtFiles, "c:\\textfiles", "txt", false);
      if(iRC)
      {
        std::cout << "Error " << iRC << std::endl;
        return -1;
      }
    
      // Print results
      for(std::vector<std::string>::iterator iterTxt = vecTxtFiles.begin();
          iterTxt != vecTxtFiles.end();
          ++iterTxt)
        std::cout << *iterTxt << std::endl;
    
      // Wait for keystroke
      _getch();
    
      return 0;
    }
    Last edited by Andreas Masur; July 24th, 2005 at 05:16 PM.

  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Code:
    class CFoo
    {
      //...
      // Operations
    public:
      static void SearchDirectory(LPCTSTR pszRootPath,
                                   CStringArray& arrFiles,
                                   bool bRecursive = true);
      //...
    };
    
    void CFoo::SearchDirectory(LPCTSTR pszRootPath, 
                               CStringArray& arrFiles,
                               bool bRecursive /*= true*/)
    {
      CString strToFind;
      strToFind.Format(_T("%s\\*.*"), pszRootPath);
       
      CFileFind ff;
      BOOL bFound = ff.FindFile(strToFind);
      while(bFound)
      {
        bFound = ff.FindNextFile();
        if(ff.IsDirectory() && !ff.IsDots())
        {
          if(true == bRecursive)
          {
            CString strRootPath = ff.GetFilePath();
            SearchDirectory(strRootPath, arrFiles, bRecursive);
          }
        }
        else if(!ff.IsDots() && !ff.IsDirectory())
        {
          CString strFilePath = ff.GetFilePath();
          arrFiles.Add(strFilePath);
        }
      }
    }
    
    void CWhateverFoo::WhateverFunction() 
    {
      //...
      CStringArray arrFiles;
      CFoo::SearchDirectory(_T("c:\\Images"), arrFiles);
      //...    
    }
    FAQ contributed by: [ovidiucucu]


    Last edited by Andreas Masur; July 24th, 2005 at 05:18 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured