style
[RRG-proxmark3.git] / client / src / scandir.c
blob8c7764730fca6caa12d71a10e6e09fd7aa7a69bc
1 //-----------------------------------------------------------------------------
2 // Borrowed initially from
3 // https://github.com/msysgit/msys/blob/master/winsup/cygwin/scandir.cc
4 // Copyright (C) 1998-2001 Red Hat, Inc. Corinna Vinschen <corinna.vinschen@cityweb.de>
5 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
6 //
7 // This program is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License as published by
9 // the Free Software Foundation, either version 3 of the License, or
10 // (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // See LICENSE.txt for the text of the license.
18 //-----------------------------------------------------------------------------
20 #include "scandir.h"
22 #ifdef _WIN32
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 int scandir(const char *dir,
29 struct dirent ***namelist,
30 int (*select)(const struct dirent *),
31 int (*compar)(const struct dirent **, const struct dirent **)) {
32 DIR *dirp;
33 struct dirent *ent, *etmp, **nl = NULL, **ntmp;
34 int count = 0;
35 int allocated = 0;
36 int err_no = 0;
38 if (!(dirp = opendir(dir)))
39 return -1;
41 while ((ent = readdir(dirp))) {
42 if (!select || select(ent)) {
44 err_no = 0;
46 if (count == allocated) {
47 if (allocated == 0)
48 allocated = 10;
49 else
50 allocated *= 2;
52 ntmp = (struct dirent **) realloc(nl, allocated * sizeof * nl);
53 if (!ntmp) {
54 err_no = 1;
55 break;
57 nl = ntmp;
60 etmp = (struct dirent *) calloc(sizeof * ent, sizeof(char));
61 if (!etmp) {
62 err_no = 1;
63 break;
65 *etmp = *ent;
66 nl[count++] = etmp;
70 if (err_no != 0) {
71 closedir(dirp);
72 if (nl) {
73 while (count > 0) {
74 free(nl[--count]);
76 free(nl);
78 return -1;
81 closedir(dirp);
83 qsort(nl, count, sizeof * nl, (int (*)(const void *, const void *)) compar);
84 if (namelist)
85 *namelist = nl;
86 return count;
88 #ifdef __cplusplus
90 #endif
92 #ifdef __cplusplus
93 extern "C" {
94 #endif
95 int alphasort(const struct dirent **a, const struct dirent **b) {
96 return strcoll((*a)->d_name, (*b)->d_name);
98 #ifdef __cplusplus
100 #endif
102 #endif // win32