scandir.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Copyright © 1995 Ian Jackson <ian@chiark.greenend.org.uk>
  5. *
  6. * This is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2,
  9. * or (at your option) any later version.
  10. *
  11. * This is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <config.h>
  20. #include <sys/types.h>
  21. #include <string.h>
  22. #include <dirent.h>
  23. #include <stdlib.h>
  24. #ifndef HAVE_SCANDIR
  25. int
  26. scandir(const char *dir, struct dirent ***namelist,
  27. int (*filter)(const struct dirent *),
  28. int (*cmp)(const void *, const void *))
  29. {
  30. DIR *d;
  31. int used, avail;
  32. struct dirent *e, *m;
  33. d = opendir(dir);
  34. if (!d)
  35. return -1;
  36. used = 0;
  37. avail = 20;
  38. *namelist = malloc(avail * sizeof(struct dirent *));
  39. if (!*namelist)
  40. return -1;
  41. while ((e = readdir(d)) != NULL) {
  42. if (filter != NULL && !filter(e))
  43. continue;
  44. m = malloc(sizeof(struct dirent) + strlen(e->d_name));
  45. if (!m)
  46. return -1;
  47. *m = *e;
  48. strcpy(m->d_name, e->d_name);
  49. if (used >= avail - 1) {
  50. avail += avail;
  51. *namelist = realloc(*namelist, avail * sizeof(struct dirent *));
  52. if (!*namelist)
  53. return -1;
  54. }
  55. (*namelist)[used] = m;
  56. used++;
  57. }
  58. (*namelist)[used] = NULL;
  59. if (cmp != NULL)
  60. qsort(*namelist, used, sizeof(struct dirent *), cmp);
  61. return used;
  62. }
  63. #endif