| 1 | // |
| 2 | // Copyright (c) 2009-2010 Mikko Mononen [email protected] |
| 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 | |
| 19 | #include "Filelist.h" |
| 20 | |
| 21 | #include <algorithm> |
| 22 | #ifdef WIN32 |
| 23 | # include <io.h> |
| 24 | #else |
| 25 | # include <dirent.h> |
| 26 | # include <cstring> |
| 27 | #endif |
| 28 | |
| 29 | using std::vector; |
| 30 | using std::string; |
| 31 | |
| 32 | void scanDirectoryAppend(const string& path, const string& ext, vector<string>& filelist) |
| 33 | { |
| 34 | #ifdef WIN32 |
| 35 | string pathWithExt = path + "/*" + ext; |
| 36 | |
| 37 | _finddata_t dir; |
| 38 | intptr_t fh = _findfirst(pathWithExt.c_str(), &dir); |
| 39 | if (fh == -1L) |
| 40 | { |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | do |
| 45 | { |
| 46 | filelist.push_back(dir.name); |
| 47 | } |
| 48 | while (_findnext(fh, &dir) == 0); |
| 49 | _findclose(fh); |
| 50 | #else |
| 51 | dirent* current = 0; |
| 52 | DIR* dp = opendir(path.c_str()); |
| 53 | if (!dp) |
| 54 | { |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | size_t extLen = strlen(ext.c_str()); |
| 59 | while ((current = readdir(dp)) != 0) |
| 60 | { |
| 61 | size_t len = strlen(current->d_name); |
| 62 | if (len > extLen && strncmp(current->d_name + len - extLen, ext.c_str(), extLen) == 0) |
| 63 | { |
| 64 | filelist.push_back(current->d_name); |
| 65 | } |
| 66 | } |
| 67 | closedir(dp); |
| 68 | #endif |
| 69 | |
| 70 | // Sort the list of files alphabetically. |
| 71 | std::sort(filelist.begin(), filelist.end()); |
| 72 | } |
| 73 | |
| 74 | void scanDirectory(const string& path, const string& ext, vector<string>& filelist) |
| 75 | { |
| 76 | filelist.clear(); |
| 77 | scanDirectoryAppend(path, ext, filelist); |
| 78 | } |