1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "list.h"
void add_file_path(Node **head, char *file_path) {
Node *new = (Node *)malloc(sizeof(Node));
if (new == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
new->file_path = strdup(file_path);
if (new->file_path == NULL) {
perror("strdup");
free(new);
exit(EXIT_FAILURE);
}
new->next = *head;
*head = new;
}
void list_files_recursively(char *base_path, Node **head, int max_depth, int current_depth) {
struct stat statbuf;
if (stat(base_path, &statbuf) == -1) {
perror("stat");
return;
}
if (S_ISREG(statbuf.st_mode)) {
add_file_path(head, base_path);
return;
}
char path[2048];
struct dirent *dp;
DIR *dir = opendir(base_path);
if (!dir)
return;
while ((dp = readdir(dir)) != NULL) {
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) {
int ret = snprintf(path, sizeof(path), "%s%s%s", base_path, (base_path[strlen(base_path) - 1] == '/' ? "" : "/"), dp->d_name);
if (ret >= (int)sizeof(path)) {
fprintf(stderr, "Path too long: %s/%s\n", base_path, dp->d_name);
continue;
}
if (stat(path, &statbuf) != -1) {
if (S_ISDIR(statbuf.st_mode)) {
if (max_depth == -1 || current_depth < max_depth) {
list_files_recursively(path, head, max_depth, current_depth + 1);
}
} else if (S_ISREG(statbuf.st_mode)) {
add_file_path(head, path);
}
}
}
}
closedir(dir);
}
void free_file_list(Node *head) {
Node *tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp->file_path);
free(tmp);
}
}
int size_of_file_list(Node *head) {
int count = 0;
Node *current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
|