home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c019 / 1.ddi / ARC521_C / SCANDIR.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-01  |  1.8 KB  |  81 lines

  1. /*
  2. **  SCANDIR
  3. **  Scan a directory, collecting all (selected) items into a an array.
  4. */
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8.  
  9. #ifdef    RCSID
  10. static char RCS[] = "$Header: scandir.c,v 1.1 87/12/29 21:35:56 rsalz Exp $";
  11. #endif    /* RCSID */
  12.  
  13. /* Initial guess at directory size. */
  14. #define INITIAL_SIZE    20
  15.  
  16. /* A convenient shorthand. */
  17. typedef struct dirent     ENTRY;
  18.         
  19. #define DIRSIZ(d) (sizeof(struct dirent) + strlen(d->d_name) + 1) 
  20.  
  21. /* Linked in later. */
  22. extern char        *malloc();
  23. extern char        *realloc();
  24. extern char        *strcpy();
  25.  
  26.  
  27. int
  28. scandir(Name, List, Selector, Sorter)
  29.     char          *Name;
  30.     ENTRY        ***List;
  31.     int             (*Selector)();
  32.     int             (*Sorter)();
  33. {
  34.     register ENTRY     **names;
  35.     register ENTRY      *E;
  36.     register DIR      *Dp;
  37.     register int       i;
  38.     register int       size;
  39.  
  40.     /* Get initial list space and open directory. */
  41.     size = INITIAL_SIZE;
  42.     if ((names = (ENTRY **)malloc(size * sizeof names[0])) == NULL
  43.      || (Dp = opendir(Name)) == NULL)
  44.     return(-1);
  45.  
  46.     /* Read entries in the directory. */
  47.     for (i = 0; E = readdir(Dp); )
  48.     if (Selector == NULL || (*Selector)(E)) {
  49.         /* User wants them all, or he wants this one. */
  50.         if (++i >= size) {
  51.         size <<= 1;
  52.         names = (ENTRY **)realloc((char *)names, size * sizeof names[0]);
  53.         if (names == NULL) {
  54.             closedir(Dp);
  55.             return(-1);
  56.         }
  57.         }
  58.  
  59.         /* Copy the entry. */
  60.         if ((names[i - 1] = (ENTRY *)malloc(DIRSIZ(E))) == NULL) { 
  61.         closedir(Dp);
  62.         return(-1);
  63.         }
  64.         names[i - 1]->d_ino = E->d_ino;
  65.         names[i - 1]->d_reclen = E->d_reclen;
  66.      /*   names[i - 1]->d_namlen = E->d_namlen; */
  67.         (void)strcpy(names[i - 1]->d_name, E->d_name);
  68.     }
  69.  
  70.     /* Close things off. */
  71.     names[i] = NULL;
  72.     *List = names;
  73.     closedir(Dp);
  74.  
  75.     /* Sort? */
  76.     if (i && Sorter)
  77.     qsort((char *)names, i, sizeof names[0], Sorter);
  78.  
  79.     return(i);
  80. }
  81.