scandir.c 2.0 KB

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