mirror of
https://github.com/AGWA/git-crypt.git
synced 2026-02-04 11:07:57 -08:00
Add get_directory_contents utility function
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
#include <fcntl.h>
|
||||
#include <windows.h>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
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<std::string> get_directory_contents (const char* path)
|
||||
{
|
||||
std::vector<std::string> 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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user