1 /*******************************************************************************
2 *                                                                              *
3 *                                   Viewmol                                    *
4 *                                                                              *
5 *                              S C A N D I R . C                               *
6 *                                                                              *
7 *                    Copyright (c) Joerg-R. Hill, May 1999                     *
8 *                                                                              *
9 ********************************************************************************
10 *
11 * $Id: scandir.c,v 1.1 1999/05/24 01:29:43 jrh Exp $
12 * $Log: scandir.c,v $
13 * Revision 1.1  1999/05/24 01:29:43  jrh
14 * Initial revision
15 *
16 */
17 #include<dirent.h>
18 #include<stdlib.h>
19 #include<string.h>
20 #include<sys/types.h>
21 
22 /* This function is only required for SunOS, all other supported OS
23    have this function in their system library */
24 
25 int
scandir(const char * dir,struct dirent *** namelist,int (* select)(const struct dirent *),int (* compar)(const struct dirent **,const struct dirent **))26 scandir (const char *dir, struct dirent ***namelist,
27 	 int (*select) (const struct dirent *),
28 	 int (*compar) (const struct dirent **, const struct dirent **))
29 {
30   DIR *d;
31   struct dirent *entry;
32   register int i = 0;
33   size_t entrysize;
34 
35   if ((d = opendir (dir)) == NULL)
36     return (-1);
37 
38   *namelist = NULL;
39   while ((entry = readdir (d)) != NULL)
40     {
41       if (select == NULL || (select != NULL && (*select) (entry)))
42 	{
43 	  *namelist = (struct dirent **) realloc ((void *) (*namelist),
44 			     (size_t) ((i + 1) * sizeof (struct dirent *)));
45 	  if (*namelist == NULL)
46 	    return (-1);
47 	  entrysize = sizeof (struct dirent) - sizeof (entry->d_name) + strlen (entry->d_na
48 								    me) + 1;
49 	  (*namelist)[i] = (struct dirent *) malloc (entrysize);
50 	  if ((*namelist)[i] == NULL)
51 	    return (-1);
52 	  memcpy ((*namelist)[i], entry, entrysize);
53 	  i++;
54 	}
55     }
56   if (closedir (d))
57     return (-1);
58   if (i == 0)
59     return (-1);
60   if (compar != NULL)
61     qsort ((void *) (*namelist), (size_t) i, sizeof (struct dirent *), compar);
62 
63   return (i);
64 }
65 
66 int
alphasort(const struct dirent ** a,const struct dirent ** b)67 alphasort (const struct dirent **a, const struct dirent **b)
68 {
69   return (strcmp ((*a)->d_name, (*b)->d_name));
70 }
71