Add get_directory_contents utility function

This commit is contained in:
Andrew Ayer
2014-07-02 22:10:09 -07:00
parent 4af0a0cfc1
commit f03d972937
3 changed files with 54 additions and 0 deletions

View File

@@ -38,6 +38,7 @@
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <dirent.h>
#include <vector>
#include <string>
#include <cstring>
@@ -296,3 +297,26 @@ int util_rename (const char* from, const char* to)
{
return rename(from, to);
}
static int dirfilter (const struct dirent* ent)
{
// filter out . and ..
return std::strcmp(ent->d_name, ".") != 0 && std::strcmp(ent->d_name, "..") != 0;
}
std::vector<std::string> get_directory_contents (const char* path)
{
struct dirent** namelist;
int n = scandir(path, &namelist, dirfilter, alphasort);
if (n == -1) {
throw System_error("scandir", path, errno);
}
std::vector<std::string> contents(n);
for (int i = 0; i < n; ++i) {
contents[i] = namelist[i]->d_name;
free(namelist[i]);
}
free(namelist);
return contents;
}