From f03d972937dbc19787ff8d1e70e26c8877f396da Mon Sep 17 00:00:00 2001 From: Andrew Ayer Date: Wed, 2 Jul 2014 22:10:09 -0700 Subject: [PATCH] Add get_directory_contents utility function --- util-unix.cpp | 24 ++++++++++++++++++++++++ util-win32.cpp | 29 +++++++++++++++++++++++++++++ util.hpp | 1 + 3 files changed, 54 insertions(+) diff --git a/util-unix.cpp b/util-unix.cpp index ec4ecfb..2385566 100644 --- a/util-unix.cpp +++ b/util-unix.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -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 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 contents(n); + for (int i = 0; i < n; ++i) { + contents[i] = namelist[i]->d_name; + free(namelist[i]); + } + free(namelist); + + return contents; +} diff --git a/util-win32.cpp b/util-win32.cpp index 6f9d358..4e6e9c1 100644 --- a/util-win32.cpp +++ b/util-win32.cpp @@ -33,6 +33,7 @@ #include #include #include +#include std::string System_error::message () const { @@ -357,3 +358,31 @@ int util_rename (const char* from, const char* to) unlink(to); return rename(from, to); } + +std::vector get_directory_contents (const char* path) +{ + std::vector filenames; + std::string patt(path); + if (!patt.empty() && patt[patt.size() - 1] != '/' && patt[patt.size() - 1] != '\\') { + patt.push_back('\\'); + } + patt.push_back('*'); + + WIN32_FIND_DATAA ffd; + HANDLE h = FindFirstFileA(patt.c_str(), &ffd); + if (h == INVALID_HANDLE_VALUE) { + throw System_error("FindFirstFileA", patt, GetLastError()); + } + do { + if (std::strcmp(ffd.cFileName, ".") != 0 && std::strcmp(ffd.cFileName, "..") != 0) { + filenames.push_back(ffd.cFileName); + } + } while (FindNextFileA(h, &ffd) != 0); + + DWORD err = GetLastError(); + if (err != ERROR_NO_MORE_FILES) { + throw System_error("FileNextFileA", patt, err); + } + FindClose(h); + return filenames; +} diff --git a/util.hpp b/util.hpp index bb79ee2..107cdfc 100644 --- a/util.hpp +++ b/util.hpp @@ -73,6 +73,7 @@ void write_be32 (std::ostream& out, uint32_t); void init_std_streams (); mode_t util_umask (mode_t); int util_rename (const char*, const char*); +std::vector get_directory_contents (const char* path); #endif