2000-02-18 03:38:33 +08:00
|
|
|
/* scandir.cc
|
|
|
|
|
|
|
|
Written by Corinna Vinschen <corinna.vinschen@cityweb.de>
|
|
|
|
|
|
|
|
This file is part of Cygwin.
|
|
|
|
|
|
|
|
This software is a copyrighted work licensed under the terms of the
|
|
|
|
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
|
|
|
|
details. */
|
|
|
|
|
2000-08-03 00:28:18 +08:00
|
|
|
#include "winsup.h"
|
2000-02-18 03:38:33 +08:00
|
|
|
#include <dirent.h>
|
|
|
|
#include <stdlib.h>
|
2000-08-22 11:58:47 +08:00
|
|
|
#include "cygerrno.h"
|
2000-02-18 03:38:33 +08:00
|
|
|
|
2001-09-19 23:54:12 +08:00
|
|
|
extern "C" int
|
|
|
|
alphasort (const struct dirent **a, const struct dirent **b)
|
|
|
|
{
|
|
|
|
return strcoll ((*a)->d_name, (*b)->d_name);
|
|
|
|
}
|
|
|
|
|
|
|
|
extern "C" int
|
2000-02-18 03:38:33 +08:00
|
|
|
scandir (const char *dir,
|
|
|
|
struct dirent ***namelist,
|
|
|
|
int (*select) (const struct dirent *),
|
|
|
|
int (*compar) (const struct dirent **, const struct dirent **))
|
|
|
|
{
|
|
|
|
DIR *dirp;
|
|
|
|
struct dirent *ent, *etmp, **nl = NULL, **ntmp;
|
|
|
|
int count = 0;
|
|
|
|
int allocated = 0;
|
2005-03-01 19:51:29 +08:00
|
|
|
int err = 0;
|
2000-02-18 03:38:33 +08:00
|
|
|
|
|
|
|
if (!(dirp = opendir (dir)))
|
|
|
|
return -1;
|
|
|
|
|
2001-09-19 23:54:12 +08:00
|
|
|
if (!compar)
|
|
|
|
compar = alphasort;
|
2000-02-18 03:38:33 +08:00
|
|
|
|
|
|
|
while ((ent = readdir (dirp)))
|
|
|
|
{
|
|
|
|
if (!select || select (ent))
|
|
|
|
{
|
|
|
|
if (count == allocated)
|
|
|
|
{
|
|
|
|
|
|
|
|
if (allocated == 0)
|
|
|
|
allocated = 10;
|
|
|
|
else
|
|
|
|
allocated *= 2;
|
|
|
|
|
|
|
|
ntmp = (struct dirent **) realloc (nl, allocated * sizeof *nl);
|
|
|
|
if (!ntmp)
|
|
|
|
{
|
2005-03-01 19:51:29 +08:00
|
|
|
err = ENOMEM;
|
2000-02-18 03:38:33 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
nl = ntmp;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!(etmp = (struct dirent *) malloc (sizeof *ent)))
|
|
|
|
{
|
2005-03-01 19:51:29 +08:00
|
|
|
err = ENOMEM;
|
2000-02-18 03:38:33 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
*etmp = *ent;
|
|
|
|
nl[count++] = etmp;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2005-03-01 19:51:29 +08:00
|
|
|
if (err != 0)
|
2000-02-18 03:38:33 +08:00
|
|
|
{
|
|
|
|
closedir (dirp);
|
|
|
|
if (nl)
|
2000-09-03 12:16:35 +08:00
|
|
|
{
|
|
|
|
while (count > 0)
|
|
|
|
free (nl[--count]);
|
|
|
|
free (nl);
|
|
|
|
}
|
2000-02-18 03:38:33 +08:00
|
|
|
/* Ignore errors from closedir() and what not else. */
|
2005-03-01 19:51:29 +08:00
|
|
|
set_errno (err);
|
2000-02-18 03:38:33 +08:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
closedir (dirp);
|
|
|
|
|
|
|
|
qsort (nl, count, sizeof *nl, (int (*)(const void *, const void *)) compar);
|
2014-05-20 18:21:34 +08:00
|
|
|
*namelist = nl;
|
2000-02-18 03:38:33 +08:00
|
|
|
return count;
|
|
|
|
}
|