2000-02-17 20:38:33 +01:00
|
|
|
/* scandir.cc
|
|
|
|
|
2013-01-21 05:38:31 +01:00
|
|
|
Copyright 1998, 1999, 2000, 2001, 2003, 2005 Red Hat, Inc.
|
2000-02-17 20:38:33 +01:00
|
|
|
|
|
|
|
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-02 18:28:18 +02:00
|
|
|
#include "winsup.h"
|
2000-02-17 20:38:33 +01:00
|
|
|
#include <dirent.h>
|
|
|
|
#include <stdlib.h>
|
2000-08-22 05:58:47 +02:00
|
|
|
#include "cygerrno.h"
|
2000-02-17 20:38:33 +01:00
|
|
|
|
2001-09-19 17:54:12 +02: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-17 20:38:33 +01: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 12:51:29 +01:00
|
|
|
int err = 0;
|
2000-02-17 20:38:33 +01:00
|
|
|
|
|
|
|
if (!(dirp = opendir (dir)))
|
|
|
|
return -1;
|
|
|
|
|
2001-09-19 17:54:12 +02:00
|
|
|
if (!compar)
|
|
|
|
compar = alphasort;
|
2000-02-17 20:38:33 +01: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 12:51:29 +01:00
|
|
|
err = ENOMEM;
|
2000-02-17 20:38:33 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
nl = ntmp;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!(etmp = (struct dirent *) malloc (sizeof *ent)))
|
|
|
|
{
|
2005-03-01 12:51:29 +01:00
|
|
|
err = ENOMEM;
|
2000-02-17 20:38:33 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
*etmp = *ent;
|
|
|
|
nl[count++] = etmp;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2005-03-01 12:51:29 +01:00
|
|
|
if (err != 0)
|
2000-02-17 20:38:33 +01:00
|
|
|
{
|
|
|
|
closedir (dirp);
|
|
|
|
if (nl)
|
2000-09-03 06:16:35 +02:00
|
|
|
{
|
|
|
|
while (count > 0)
|
|
|
|
free (nl[--count]);
|
|
|
|
free (nl);
|
|
|
|
}
|
2000-02-17 20:38:33 +01:00
|
|
|
/* Ignore errors from closedir() and what not else. */
|
2005-03-01 12:51:29 +01:00
|
|
|
set_errno (err);
|
2000-02-17 20:38:33 +01:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
closedir (dirp);
|
|
|
|
|
|
|
|
qsort (nl, count, sizeof *nl, (int (*)(const void *, const void *)) compar);
|
|
|
|
if (namelist)
|
|
|
|
*namelist = nl;
|
|
|
|
return count;
|
|
|
|
}
|