diff --git a/list.h b/list.h index a090f8d..1f7b8a8 100644 --- a/list.h +++ b/list.h @@ -3,13 +3,19 @@ #include #include +#define MAX_FILES 200 static 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)); } - (*files)[*size] = strdup(name); + if (*size == MAX_FILES) + (*files)[*size] = strdup("...too many to list..."); + else + (*files)[*size] = strdup(name); (*size)++; } @@ -18,35 +24,31 @@ static 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) { - char path[1024]; if (entry->d_type == DT_DIR) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; - snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); + 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); } - -/*int main(int argc, char *argv[]) { - int capacity = 32, size = 0; - char **files = malloc(sizeof(char*)*capacity); - for (int i = 1; i < argc; i++) { - add_files(argv[i], &files, &size, &capacity); - } - - for (int f = 0; f < size; f++) { - printf("%s\n", files[f]); - } - return 0; -}*/