Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
CTCaer
GitHub Repository: CTCaer/hekate
Path: blob/master/bdk/utils/dirlist.c
1476 views
1
/*
2
* Copyright (c) 2018-2025 CTCaer
3
*
4
* This program is free software; you can redistribute it and/or modify it
5
* under the terms and conditions of the GNU General Public License,
6
* version 2, as published by the Free Software Foundation.
7
*
8
* This program is distributed in the hope it will be useful, but WITHOUT
9
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11
* more details.
12
*
13
* You should have received a copy of the GNU General Public License
14
* along with this program. If not, see <http://www.gnu.org/licenses/>.
15
*/
16
17
#include <string.h>
18
#include <stdlib.h>
19
20
#include "dirlist.h"
21
#include <libs/fatfs/ff.h>
22
#include <mem/heap.h>
23
#include <utils/types.h>
24
25
dirlist_t *dirlist(const char *directory, const char *pattern, bool includeHiddenFiles, bool parse_dirs)
26
{
27
int res = 0;
28
u32 k = 0;
29
DIR dir;
30
FILINFO fno;
31
32
dirlist_t *dir_entries = (dirlist_t *)malloc(sizeof(dirlist_t));
33
34
// Setup pointer tree.
35
for (u32 i = 0; i < DIR_MAX_ENTRIES; i++)
36
dir_entries->name[i] = &dir_entries->data[i * 256];
37
38
if (!pattern && !f_opendir(&dir, directory))
39
{
40
for (;;)
41
{
42
res = f_readdir(&dir, &fno);
43
if (res || !fno.fname[0])
44
break;
45
46
bool curr_parse = parse_dirs ? (fno.fattrib & AM_DIR) : !(fno.fattrib & AM_DIR);
47
48
if (curr_parse)
49
{
50
if ((fno.fname[0] != '.') && (includeHiddenFiles || !(fno.fattrib & AM_HID)))
51
{
52
strcpy(&dir_entries->data[k * 256], fno.fname);
53
if (++k >= DIR_MAX_ENTRIES)
54
break;
55
}
56
}
57
}
58
f_closedir(&dir);
59
}
60
else if (pattern && !f_findfirst(&dir, &fno, directory, pattern) && fno.fname[0])
61
{
62
do
63
{
64
if (!(fno.fattrib & AM_DIR) && (fno.fname[0] != '.') && (includeHiddenFiles || !(fno.fattrib & AM_HID)))
65
{
66
strcpy(&dir_entries->data[k * 256], fno.fname);
67
if (++k >= DIR_MAX_ENTRIES)
68
break;
69
}
70
res = f_findnext(&dir, &fno);
71
} while (fno.fname[0] && !res);
72
f_closedir(&dir);
73
}
74
75
if (!k)
76
{
77
free(dir_entries);
78
79
return NULL;
80
}
81
82
// Terminate name list.
83
dir_entries->name[k] = NULL;
84
85
// Reorder ini files Alphabetically.
86
for (u32 i = 0; i < k - 1 ; i++)
87
{
88
for (u32 j = i + 1; j < k; j++)
89
{
90
if (strcasecmp(dir_entries->name[i], dir_entries->name[j]) > 0)
91
{
92
char *tmp = dir_entries->name[i];
93
dir_entries->name[i] = dir_entries->name[j];
94
dir_entries->name[j] = tmp;
95
}
96
}
97
}
98
99
return dir_entries;
100
}
101
102