Cygwin: strptime: add release note
[newlib-cygwin.git] / winsup / cygwin / scandir.cc
blobd6ac64907b9c1a89d17a73ce00ad8c50bae6a26a
1 /* scandir.cc
3 Written by Corinna Vinschen <corinna.vinschen@cityweb.de>
5 This file is part of Cygwin.
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
9 details. */
11 #include "winsup.h"
12 #include <dirent.h>
13 #include <stdlib.h>
14 #include "cygerrno.h"
16 extern "C" int
17 alphasort (const struct dirent **a, const struct dirent **b)
19 return strcoll ((*a)->d_name, (*b)->d_name);
22 extern "C" int
23 versionsort (const struct dirent **a, const struct dirent **b)
25 return strverscmp ((*a)->d_name, (*b)->d_name);
28 extern "C" int
29 scandir (const char *dir,
30 struct dirent ***namelist,
31 int (*select) (const struct dirent *),
32 int (*compar) (const struct dirent **, const struct dirent **))
34 DIR *dirp;
35 struct dirent *ent, *etmp, **nl = NULL, **ntmp;
36 int count = 0;
37 int allocated = 0;
38 int err = 0;
40 if (!(dirp = opendir (dir)))
41 return -1;
43 if (!compar)
44 compar = alphasort;
46 while ((ent = readdir (dirp)))
48 if (!select || select (ent))
50 if (count == allocated)
53 if (allocated == 0)
54 allocated = 10;
55 else
56 allocated *= 2;
58 ntmp = (struct dirent **) realloc (nl, allocated * sizeof *nl);
59 if (!ntmp)
61 err = ENOMEM;
62 break;
64 nl = ntmp;
67 if (!(etmp = (struct dirent *) malloc (sizeof *ent)))
69 err = ENOMEM;
70 break;
72 *etmp = *ent;
73 nl[count++] = etmp;
77 if (err != 0)
79 closedir (dirp);
80 if (nl)
82 while (count > 0)
83 free (nl[--count]);
84 free (nl);
86 /* Ignore errors from closedir() and what not else. */
87 set_errno (err);
88 return -1;
91 closedir (dirp);
93 qsort (nl, count, sizeof *nl, (int (*)(const void *, const void *)) compar);
94 *namelist = nl;
95 return count;