summaryrefslogtreecommitdiffstats
path: root/usr/klibc/scandir.c
blob: 9b9598039d6daaa2bb04a467fc54ea9596c8d5f2 (plain)
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
/*
 * scandir.c: scandir
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <dirent.h>

int scandir(const char *dirp, struct dirent ***namelist,
	    int (*filter)(const struct dirent *),
	    int (*compar)(const struct dirent **, const struct dirent **))
{
	struct dirent **nl = NULL, **next_nl;
	struct dirent *dirent;
	size_t count = 0;
	size_t allocated = 0;
	DIR *dir;

	dir = opendir(dirp);
	if (!dir)
		return -1;

	while (1) {
		dirent = readdir(dir);
		if (!dirent)
			break;
		if (!filter || filter(dirent)) {
			struct dirent *copy;
			copy = malloc(sizeof(*copy));
			if (!copy)
				goto cleanup_fail;
			memcpy(copy, dirent, sizeof(*copy));

			/* Extend the array if needed */
			if (count == allocated) {
				if (allocated == 0)
					allocated = 15; /* ~1 page worth */
				else
					allocated *= 2;
				next_nl = realloc(nl, allocated);
				if (!next_nl) {
					free(copy);
					goto cleanup_fail;
				}
				nl = next_nl;
			}

			nl[count++] = copy;
		}
	}

	qsort(nl, count, sizeof(struct dirent *),
	      (int (*)(const void *, const void *))compar);

	closedir(dir);

	*namelist = nl;
	return count;

cleanup_fail:
	while (count) {
		dirent = nl[--count];
		free(dirent);
	}
	free(nl);
	closedir(dir);
	errno = ENOMEM;
	return -1;
}