C++ POSIX compliant way of reading a directory listing.
An algorithm I posted in answer to a question on
http://www.experts-exchange.com/
#include <dirent.h>
#include <vector>
#include <string>
using namespace std;
/**
* Read a directory listing into a vector of strings, filtered by file extension.
* Throws std::exception on error.
**/
std::vector<std::string> readDirectory(const std::string &directoryLocation, const std::string &extension)
{
vector<string> result;
string lcExtension( strToLower(extension) );
DIR *dir;
struct dirent *ent;
if ((dir = opendir(directoryLocation.c_str())) == NULL) {
throw std::exception("readDirectory() - Unable to open directory.");
}
while ((ent = readdir(dir)) != NULL)
{
string entry( ent->d_name );
string lcEntry( strToLower(entry) );
// Check extension matches (case insensitive)
size_t pos = lcEntry.rfind(lcExtension);
if (pos!=string::npos && pos==lcEntry.length()-lcExtension.length()) {
result.push_back( entry );
}
}
if (closedir(dir) != 0) {
throw std::exception("readDirectory() - Unable to close directory.");
}
return result;
}