59 lines
1.6 KiB
C
59 lines
1.6 KiB
C
/**
|
|
* Helper functions for adding files to a dynamically resizing array.
|
|
*/
|
|
#include <dirent.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
#define MAX_FILES 200
|
|
|
|
void add_file(char *name, char ***files, int *size, int *capacity)
|
|
{
|
|
// Prevent from taking too long
|
|
if (*size > MAX_FILES) return;
|
|
if (*size == *capacity) {
|
|
*capacity *= 2;
|
|
*files = realloc(*files, sizeof(char*) * (*capacity));
|
|
}
|
|
if (*size == MAX_FILES)
|
|
(*files)[*size] = strdup("...too many to list...");
|
|
else
|
|
(*files)[*size] = strdup(name);
|
|
(*size)++;
|
|
}
|
|
|
|
void add_files(char *name, char ***files, int *size, int *capacity)
|
|
{
|
|
DIR *dir;
|
|
struct dirent *entry;
|
|
|
|
// Prevent from taking too long
|
|
if (*size > MAX_FILES) return;
|
|
|
|
add_file(name, files, size, capacity);
|
|
if (!(dir = opendir(name))) {
|
|
return;
|
|
}
|
|
|
|
char path[1024];
|
|
while ((entry = readdir(dir)) != NULL) {
|
|
if (entry->d_type == DT_DIR) {
|
|
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
|
continue;
|
|
if (name[strlen(name)-1] == '/')
|
|
snprintf(path, sizeof(path), "%s%s", name, entry->d_name);
|
|
else
|
|
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
|
|
add_files(path, files, size, capacity);
|
|
} else {
|
|
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
|
|
add_file(path, files, size, capacity);
|
|
}
|
|
|
|
// Prevent from taking too long
|
|
if (*size > MAX_FILES) return;
|
|
}
|
|
closedir(dir);
|
|
}
|