Filelist.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include "Filelist.h"
  19. #include <algorithm>
  20. #ifdef WIN32
  21. # include <io.h>
  22. #else
  23. # include <dirent.h>
  24. # include <cstring>
  25. #endif
  26. using std::vector;
  27. using std::string;
  28. void scanDirectoryAppend(const string& path, const string& ext, vector<string>& filelist)
  29. {
  30. #ifdef WIN32
  31. string pathWithExt = path + "/*" + ext;
  32. _finddata_t dir;
  33. intptr_t fh = _findfirst(pathWithExt.c_str(), &dir);
  34. if (fh == -1L)
  35. {
  36. return;
  37. }
  38. do
  39. {
  40. filelist.push_back(dir.name);
  41. }
  42. while (_findnext(fh, &dir) == 0);
  43. _findclose(fh);
  44. #else
  45. dirent* current = 0;
  46. DIR* dp = opendir(path.c_str());
  47. if (!dp)
  48. {
  49. return;
  50. }
  51. int extLen = strlen(ext.c_str());
  52. while ((current = readdir(dp)) != 0)
  53. {
  54. int len = strlen(current->d_name);
  55. if (len > extLen && strncmp(current->d_name + len - extLen, ext.c_str(), extLen) == 0)
  56. {
  57. filelist.push_back(current->d_name);
  58. }
  59. }
  60. closedir(dp);
  61. #endif
  62. // Sort the list of files alphabetically.
  63. std::sort(filelist.begin(), filelist.end());
  64. }
  65. void scanDirectory(const string& path, const string& ext, vector<string>& filelist)
  66. {
  67. filelist.clear();
  68. scanDirectoryAppend(path, ext, filelist);
  69. }