home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / ARC521-2.ZIP / SCANDIR.C < prev   
C/C++ Source or Header  |  1989-12-29  |  1KB  |  69 lines

  1. /*
  2.  *  SCANDIR
  3.  *  Scan a directory, collecting all (selected) items into a an array.
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10. #include <sys/dir.h>
  11.  
  12.  
  13. #define INITIAL_SIZE    20
  14. #define DIRSIZ(d) (sizeof(struct direct))
  15.  
  16.  
  17. int scandir(char *Name, struct direct ***List,
  18.             int (*Selector)(struct direct *), int (*Sorter)())
  19. {
  20.   DIR *Dp;
  21.   struct direct **names, *E;
  22.   int i, size;
  23.  
  24.   /* Get initial list space and open directory. */
  25.   size = INITIAL_SIZE;
  26.  
  27.   if ( (names = malloc(size * sizeof names[0])) == NULL
  28.        || (Dp = opendir(Name)) == NULL )
  29.     return -1;
  30.  
  31.   /* Read entries in the directory. */
  32.   for ( i = 0; E = readdir(Dp); )
  33.     if ( Selector == NULL || (*Selector)(E) )
  34.     {
  35.       /* User wants them all, or he wants this one. */
  36.       if (++i >= size)
  37.       {
  38.         size <<= 1;
  39.         names = realloc(names, size * sizeof names[0]);
  40.  
  41.         if (names == NULL)
  42.         {
  43.           closedir(Dp);
  44.           return -1;
  45.         }
  46.       }
  47.  
  48.       /* Copy the struct direct. */
  49.       if ( (names[i - 1] = malloc(sizeof(struct direct))) == NULL)
  50.       {
  51.         closedir(Dp);
  52.         return -1;
  53.       }
  54.  
  55.       *names[i - 1] = *E;
  56.     }
  57.  
  58.   /* Close things off. */
  59.   names[i] = NULL;
  60.   *List = names;
  61.   closedir(Dp);
  62.  
  63.   /* Sort? */
  64.   if (i && Sorter)
  65.     qsort((char *)names, i, sizeof names[0], Sorter);
  66.  
  67.   return i;
  68. }
  69.