1 /* Copyright (C) 1992-1998,2000,2002,2003,2009 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
23 #include <bits/libc-lock.h>
26 #define SCANDIR scandir
27 #define READDIR __readdir
28 #define DIRENT_TYPE struct dirent
31 #ifndef SCANDIR_CANCEL
32 #define SCANDIR_CANCEL
33 struct scandir_cancel_struct
41 cancel_handler (void *arg)
43 struct scandir_cancel_struct *cp = arg;
47 for (i = 0; i < cp->cnt; ++i)
50 (void) __closedir (cp->dp);
56 SCANDIR (dir, namelist, select, cmp)
58 DIRENT_TYPE ***namelist;
59 int (*select) (const DIRENT_TYPE *);
60 int (*cmp) (const DIRENT_TYPE **, const DIRENT_TYPE **);
62 DIR *dp = __opendir (dir);
63 DIRENT_TYPE **v = NULL;
65 struct scandir_cancel_struct c;
78 __libc_cleanup_push (cancel_handler, &c);
80 while ((d = READDIR (dp)) != NULL)
82 int use_it = select == NULL;
87 /* The select function might have changed errno. It was
88 zero before and it need to be again to make the latter
98 /* Ignore errors from select or readdir */
101 if (__builtin_expect (c.cnt == vsize, 0))
108 new = (DIRENT_TYPE **) realloc (v, vsize * sizeof (*v));
115 dsize = &d->d_name[_D_ALLOC_NAMLEN (d)] - (char *) d;
116 vnew = (DIRENT_TYPE *) malloc (dsize);
120 v[c.cnt++] = (DIRENT_TYPE *) memcpy (vnew, d, dsize);
124 if (__builtin_expect (errno, 0) != 0)
135 /* Sort the list if we have a comparison function to sort with. */
137 qsort (v, c.cnt, sizeof (*v),
138 (int (*) (const void *, const void *)) cmp);
143 __libc_cleanup_pop (0);
145 (void) __closedir (dp);