-
Notifications
You must be signed in to change notification settings - Fork 0
/
Directory.c
115 lines (88 loc) · 2.42 KB
/
Directory.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "Directory.h"
#include "debugmalloc.h"
#ifdef __WINDOWS__
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
FileList dir_getfiles(char *path) {
size_t length;
StringCchLength(path, MAX_PATH, &length);
if (length > MAX_PATH - 3)
return (FileList){NULL, 0};
TCHAR dir[MAX_PATH];
StringCchCopy(dir, MAX_PATH, path);
StringCchCat(dir, MAX_PATH, TEXT("\\*"));
WIN32_FIND_DATA findData;
HANDLE hFind = FindFirstFile(dir, &findData);
if (hFind == INVALID_HANDLE_VALUE)
return (FileList){NULL, 0};
size_t num = 0;
char **results = NULL;
do {
if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
num++;
char **newMem = (char **)realloc(results, sizeof(char *) * num);
if (newMem == NULL) {
log_error("Couldn't allocate new memory!\n");
num--;
return (FileList){results, num};
}
results = newMem;
size_t len = strlen(findData.cFileName) + 1;
results[num - 1] = (char *)malloc(sizeof(char) * len);
StringCchCopy(results[num - 1], len, findData.cFileName);
}
} while (FindNextFile(hFind, &findData) != 0);
return (FileList){results, num};
}
#else
#include <dirent.h>
#include <sys/stat.h>
FileList dir_getfiles(char *path) {
DIR *dir = opendir(path);
if (!dir)
return (FileList){NULL, 0};
size_t num = 0;
char **results = NULL;
size_t pathLen = strlen(path);
for (struct dirent *ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
char *fullPath = (char *)malloc(sizeof(char) * (pathLen + strlen(ent->d_name) + 2));
strcpy(fullPath, path);
strcat(fullPath, "/");
strcat(fullPath, ent->d_name);
struct stat fileStat;
stat(fullPath, &fileStat);
free(fullPath);
if (S_ISREG(fileStat.st_mode)) {
num++;
char **newMem = (char **)realloc(results, sizeof(char *) * num);
if (newMem == NULL) {
log_error("Couldn't allocate new memory!\n");
num--;
return (FileList){results, num};
}
results = newMem;
size_t len = strlen(ent->d_name) + 1;
results[num - 1] = (char *)malloc(sizeof(char) * len);
strcpy(results[num - 1], ent->d_name);
}
}
closedir(dir);
return (FileList) {results, num};
}
#endif
void dir_free_filelist(FileList *fileList) {
for (size_t i = 0; i < fileList->num; i++) {
free((fileList->files)[i]);
}
free(fileList->files);
}
void dir_remove_extension(char *file) {
size_t len = strlen(file);
for (size_t i = len; i > 0; i--) {
if (file[i] == '.') {
file[i] = '\0';
return;
}
}
}