From cbffab246997fb5a06211dfb706b54e5ae5bb59f Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 16:58:51 +0200 Subject: Adding upstream version 1.21.22. Signed-off-by: Daniel Baumann --- lib/compat/scandir.c | 99 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 lib/compat/scandir.c (limited to 'lib/compat/scandir.c') diff --git a/lib/compat/scandir.c b/lib/compat/scandir.c new file mode 100644 index 0000000..8771de0 --- /dev/null +++ b/lib/compat/scandir.c @@ -0,0 +1,99 @@ +/* + * libcompat - system compatibility library + * + * Copyright © 1995 Ian Jackson + * Copyright © 2008, 2009 Guillem Jover + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include + +#include +#include +#include + +#include "compat.h" + +static int +cleanup(DIR *dir, struct dirent **dirlist, int used) +{ + if (dir) + closedir(dir); + + if (dirlist) { + int i; + + for (i = 0; i < used; i++) + free(dirlist[i]); + free(dirlist); + } + + return -1; +} + +int +scandir(const char *dir, struct dirent ***namelist, + int (*filter)(const struct dirent *), + int (*cmp)(const void *, const void *)) +{ + DIR *d; + struct dirent *e, *m, **list; + int used, avail; + + d = opendir(dir); + if (!d) + return -1; + + list = NULL; + used = avail = 0; + + while ((e = readdir(d)) != NULL) { + if (filter != NULL && !filter(e)) + continue; + + if (used >= avail - 1) { + struct dirent **newlist; + + if (avail) + avail *= 2; + else + avail = 20; + newlist = realloc(list, avail * sizeof(*newlist)); + if (!newlist) + return cleanup(d, list, used); + list = newlist; + } + + m = malloc(sizeof(*m) + strlen(e->d_name)); + if (!m) + return cleanup(d, list, used); + *m = *e; + strcpy(m->d_name, e->d_name); + + list[used] = m; + used++; + } + + closedir(d); + + if (list != NULL && cmp != NULL) + qsort(list, used, sizeof(list[0]), cmp); + + *namelist = list; + + return used; +} -- cgit v1.2.3