file_search.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include "common/common.h"
  5. #include "common/common_paths.h"
  6. #ifndef _WIN32
  7. #include <sys/types.h>
  8. #include <dirent.h>
  9. #else
  10. #include <windows.h>
  11. #endif
  12. #include <string>
  13. #include <algorithm>
  14. #include "common/file_search.h"
  15. #include "common/string_util.h"
  16. CFileSearch::CFileSearch(const CFileSearch::XStringVector& _rSearchStrings, const CFileSearch::XStringVector& _rDirectories)
  17. {
  18. // Reverse the loop order for speed?
  19. for (size_t j = 0; j < _rSearchStrings.size(); j++)
  20. {
  21. for (size_t i = 0; i < _rDirectories.size(); i++)
  22. {
  23. FindFiles(_rSearchStrings[j], _rDirectories[i]);
  24. }
  25. }
  26. }
  27. void CFileSearch::FindFiles(const std::string& _searchString, const std::string& _strPath)
  28. {
  29. std::string GCMSearchPath;
  30. Common::BuildCompleteFilename(GCMSearchPath, _strPath, _searchString);
  31. #ifdef _WIN32
  32. WIN32_FIND_DATA findData;
  33. HANDLE FindFirst = FindFirstFile(Common::UTF8ToTStr(GCMSearchPath).c_str(), &findData);
  34. if (FindFirst != INVALID_HANDLE_VALUE)
  35. {
  36. bool bkeepLooping = true;
  37. while (bkeepLooping)
  38. {
  39. if (findData.cFileName[0] != '.')
  40. {
  41. std::string strFilename;
  42. Common::BuildCompleteFilename(strFilename, _strPath, Common::TStrToUTF8(findData.cFileName));
  43. m_FileNames.push_back(strFilename);
  44. }
  45. bkeepLooping = FindNextFile(FindFirst, &findData) ? true : false;
  46. }
  47. }
  48. FindClose(FindFirst);
  49. #else
  50. // TODO: super lame/broken
  51. auto end_match(_searchString);
  52. // assuming we have a "*.blah"-like pattern
  53. if (!end_match.empty() && end_match[0] == '*')
  54. end_match.erase(0, 1);
  55. // ugly
  56. if (end_match == ".*")
  57. end_match.clear();
  58. DIR* dir = opendir(_strPath.c_str());
  59. if (!dir)
  60. return;
  61. while (auto const dp = readdir(dir))
  62. {
  63. std::string found(dp->d_name);
  64. if ((found != ".") && (found != "..")
  65. && (found.size() >= end_match.size())
  66. && std::equal(end_match.rbegin(), end_match.rend(), found.rbegin()))
  67. {
  68. std::string full_name;
  69. if (_strPath.c_str()[_strPath.size()-1] == DIR_SEP_CHR)
  70. full_name = _strPath + found;
  71. else
  72. full_name = _strPath + DIR_SEP + found;
  73. m_FileNames.push_back(full_name);
  74. }
  75. }
  76. closedir(dir);
  77. #endif
  78. }
  79. const CFileSearch::XStringVector& CFileSearch::GetFileNames() const
  80. {
  81. return m_FileNames;
  82. }