scandir.c 1.0 KB
Newer Older
R
Rich Felker 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
#include <stddef.h>
#include <libc.h>

int scandir(const char *path, struct dirent ***res,
	int (*sel)(const struct dirent *),
	int (*cmp)(const struct dirent **, const struct dirent **))
{
	DIR *d = opendir(path);
	struct dirent *de, **names=0, **tmp;
15
	size_t cnt=0, len=0;
R
Rich Felker 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28
	int old_errno = errno;

	if (!d) return -1;

	while ((errno=0), (de = readdir(d))) {
		if (sel && !sel(de)) continue;
		if (cnt >= len) {
			len = 2*len+1;
			if (len > SIZE_MAX/sizeof *names) break;
			tmp = realloc(names, len * sizeof *names);
			if (!tmp) break;
			names = tmp;
		}
29
		names[cnt] = malloc(de->d_reclen);
R
Rich Felker 已提交
30
		if (!names[cnt]) break;
31
		memcpy(names[cnt++], de, de->d_reclen);
R
Rich Felker 已提交
32 33 34 35 36 37 38 39 40
	}

	closedir(d);

	if (errno) {
		if (names) while (cnt-->0) free(names[cnt]);
		free(names);
		return -1;
	}
R
Rich Felker 已提交
41
	errno = old_errno;
R
Rich Felker 已提交
42 43 44 45 46 47 48

	if (cmp) qsort(names, cnt, sizeof *names, (int (*)(const void *, const void *))cmp);
	*res = names;
	return cnt;
}

LFS64(scandir);