scandir.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright (C) 2000-2011 Erik Andersen <andersen@uclibc.org>
  3. *
  4. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  5. */
  6. #include <dirent.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9. #include <errno.h>
  10. #include "dirstream.h"
  11. #ifndef __SCANDIR
  12. # define __SCANDIR scandir
  13. # define __DIRENT_TYPE struct dirent
  14. # define __READDIR readdir
  15. #endif
  16. int __SCANDIR(const char *dir, __DIRENT_TYPE ***namelist,
  17. int (*selector) (const __DIRENT_TYPE *),
  18. int (*compar) (const __DIRENT_TYPE **, const __DIRENT_TYPE **))
  19. {
  20. DIR *dp = opendir (dir);
  21. __DIRENT_TYPE *current;
  22. __DIRENT_TYPE **names = NULL;
  23. size_t names_size = 0, pos;
  24. int save;
  25. if (dp == NULL)
  26. return -1;
  27. save = errno;
  28. __set_errno (0);
  29. pos = 0;
  30. while ((current = __READDIR (dp)) != NULL) {
  31. int use_it = selector == NULL;
  32. if (! use_it)
  33. {
  34. use_it = (*selector) (current);
  35. /* The selector function might have changed errno.
  36. * It was zero before and it need to be again to make
  37. * the latter tests work. */
  38. if (! use_it)
  39. __set_errno (0);
  40. }
  41. if (use_it)
  42. {
  43. __DIRENT_TYPE *vnew;
  44. size_t dsize;
  45. /* Ignore errors from selector or readdir */
  46. __set_errno (0);
  47. if (unlikely(pos == names_size))
  48. {
  49. __DIRENT_TYPE **new;
  50. if (names_size == 0)
  51. names_size = 10;
  52. else
  53. names_size *= 2;
  54. new = (__DIRENT_TYPE **) realloc (names,
  55. names_size * sizeof (__DIRENT_TYPE *));
  56. if (new == NULL)
  57. break;
  58. names = new;
  59. }
  60. dsize = &current->d_name[_D_ALLOC_NAMLEN(current)] - (char*)current;
  61. vnew = (__DIRENT_TYPE *) malloc (dsize);
  62. if (vnew == NULL)
  63. break;
  64. names[pos++] = (__DIRENT_TYPE *) memcpy (vnew, current, dsize);
  65. }
  66. }
  67. if (unlikely(errno != 0))
  68. {
  69. save = errno;
  70. closedir (dp);
  71. while (pos > 0)
  72. free (names[--pos]);
  73. free (names);
  74. __set_errno (save);
  75. return -1;
  76. }
  77. closedir (dp);
  78. __set_errno (save);
  79. /* Sort the list if we have a comparison function to sort with. */
  80. if (compar != NULL)
  81. qsort (names, pos, sizeof (__DIRENT_TYPE *), (comparison_fn_t) compar);
  82. *namelist = names;
  83. return pos;
  84. }
  85. #if __WORDSIZE == 64
  86. strong_alias_untyped(scandir,scandir64)
  87. #endif