Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
CTCaer
GitHub Repository: CTCaer/hekate
Path: blob/master/bdk/utils/dirlist.c
3694 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, u32 flags)
26
{
27
int res = 0;
28
u32 k = 0;
29
DIR dir;
30
FILINFO fno;
31
bool show_hidden = !!(flags & DIR_SHOW_HIDDEN);
32
bool show_dirs = !!(flags & DIR_SHOW_DIRS);
33
bool ascii_order = !!(flags & DIR_ASCII_ORDER);
34
35
dirlist_t *dir_entries = (dirlist_t *)malloc(sizeof(dirlist_t));
36
37
// Setup pointer tree.
38
for (u32 i = 0; i < DIR_MAX_ENTRIES; i++)
39
dir_entries->name[i] = &dir_entries->data[i * 256];
40
41
if (!pattern && !f_opendir(&dir, directory))
42
{
43
for (;;)
44
{
45
res = f_readdir(&dir, &fno);
46
if (res || !fno.fname[0])
47
break;
48
49
bool curr_parse = show_dirs ? (fno.fattrib & AM_DIR) : !(fno.fattrib & AM_DIR);
50
51
if (curr_parse)
52
{
53
if ((fno.fname[0] != '.') && (show_hidden || !(fno.fattrib & AM_HID)))
54
{
55
strcpy(&dir_entries->data[k * 256], fno.fname);
56
if (++k >= DIR_MAX_ENTRIES)
57
break;
58
}
59
}
60
}
61
f_closedir(&dir);
62
}
63
else if (pattern && !f_findfirst(&dir, &fno, directory, pattern) && fno.fname[0])
64
{
65
do
66
{
67
if (!(fno.fattrib & AM_DIR) && (fno.fname[0] != '.') && (show_hidden || !(fno.fattrib & AM_HID)))
68
{
69
strcpy(&dir_entries->data[k * 256], fno.fname);
70
if (++k >= DIR_MAX_ENTRIES)
71
break;
72
}
73
res = f_findnext(&dir, &fno);
74
} while (fno.fname[0] && !res);
75
f_closedir(&dir);
76
}
77
78
if (!k)
79
{
80
free(dir_entries);
81
82
return NULL;
83
}
84
85
// Terminate name list.
86
dir_entries->name[k] = NULL;
87
88
// Choose list ordering.
89
int (*strcmpex)(const char* str1, const char* str2) = ascii_order ? strcmp : strcasecmp;
90
91
// Reorder ini files Alphabetically.
92
for (u32 i = 0; i < k - 1 ; i++)
93
{
94
for (u32 j = i + 1; j < k; j++)
95
{
96
if (strcmpex(dir_entries->name[i], dir_entries->name[j]) > 0)
97
{
98
char *tmp = dir_entries->name[i];
99
dir_entries->name[i] = dir_entries->name[j];
100
dir_entries->name[j] = tmp;
101
}
102
}
103
}
104
105
return dir_entries;
106
}
107
108