1

我有一个程序可以成功搜索特定驱动器中特定扩展名的文件(我正在使用 Windows),让我们说它是“C:\”,然后在控制台上打印这些文件。现在我想概括我的程序。我希望我的程序将在所有分区(驱动器)中搜索..我该怎么做..我应该使用哪个函数..这是我的代码示例

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:", "apk");
  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:", "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;
}
4

1 回答 1

1

我不是 Windows 程序员,但看起来您必须找出系统中可用的驱动器并为所有驱动器调用您的函数。请参阅此处如何获取 Windows 上的可用驱动器列表:枚举 Windows 中的所有可用驱动器号

于 2013-08-07T09:42:17.620 回答