summaryrefslogtreecommitdiffstats
path: root/util.c
diff options
context:
space:
mode:
authorBert <ber.t@gmx.com>2011-04-07 19:15:00 +0200
committerBert <ber.t@gmx.com>2011-04-07 19:15:00 +0200
commite9996882cb55c5b6974a3448f29bda32d6aa373d (patch)
tree28585b374cc4b09443449ec767b67e0c954cd7eb /util.c
parent7d40faeba6076477645e36034b58e4bf82d4a96c (diff)
downloadnsxiv-e9996882cb55c5b6974a3448f29bda32d6aa373d.tar.zst
Moved read_dir_rec into util.c
Diffstat (limited to 'util.c')
-rw-r--r--util.c79
1 files changed, 79 insertions, 0 deletions
diff --git a/util.c b/util.c
index 42d1384..a8ebe73 100644
--- a/util.c
+++ b/util.c
@@ -18,6 +18,7 @@
#include <stdlib.h>
#include <string.h>
+#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -26,6 +27,8 @@
#include "options.h"
#include "util.h"
+#define DNAME_CNT 512
+#define FNAME_CNT 1024
#define FNAME_LEN 1024
void cleanup();
@@ -199,6 +202,82 @@ int create_dir_rec(const char *path) {
return err;
}
+int fncmp(const void *a, const void *b) {
+ return strcoll(*((char* const*) a), *((char* const*) b));
+}
+
+char** read_dir_rec(const char *dirname) {
+ int dcnt, didx, fcnt, fidx;
+ char **dnames, **fnames, *filename;
+ unsigned char first;
+ size_t len;
+ DIR *dir;
+ struct dirent *dentry;
+ struct stat fstats;
+
+ if (!dirname)
+ return NULL;
+
+ dcnt = DNAME_CNT;
+ didx = first = 1;
+ dnames = (char**) s_malloc(dcnt * sizeof(char*));
+ dnames[0] = (char*) dirname;
+
+ fcnt = FNAME_CNT;
+ fidx = 0;
+ fnames = (char**) s_malloc(fcnt * sizeof(char*));
+
+ while (didx > 0) {
+ dirname = dnames[--didx];
+ if (!(dir = opendir(dirname))) {
+ warn("could not open directory: %s", dirname);
+ } else {
+ while ((dentry = readdir(dir))) {
+ if (!strcmp(dentry->d_name, ".") || !strcmp(dentry->d_name, ".."))
+ continue;
+
+ len = strlen(dirname) + strlen(dentry->d_name) + 2;
+ filename = (char*) s_malloc(len * sizeof(char));
+ snprintf(filename, len, "%s%s%s", dirname,
+ dirname[strlen(dirname)-1] == '/' ? "" : "/", dentry->d_name);
+
+ if (!stat(filename, &fstats) && S_ISDIR(fstats.st_mode)) {
+ if (didx == dcnt) {
+ dcnt *= 2;
+ dnames = (char**) s_realloc(dnames, dcnt * sizeof(char*));
+ }
+ dnames[didx++] = filename;
+ } else {
+ if (fidx + 1 == fcnt) {
+ fcnt *= 2;
+ fnames = (char**) s_realloc(fnames, fcnt * sizeof(char*));
+ }
+ fnames[fidx++] = filename;
+ }
+ }
+ closedir(dir);
+ }
+
+ if (!first)
+ free((void*) dirname);
+ else
+ first = 0;
+ }
+
+ if (!fidx) {
+ free(fnames);
+ fnames = NULL;
+ } else {
+ if (fidx > 1)
+ qsort(fnames, fidx, sizeof(char*), fncmp);
+ fnames[fidx] = NULL;
+ }
+
+ free(dnames);
+
+ return fnames;
+}
+
char* readline(FILE *stream) {
size_t len;
char *buf, *s, *end;