scandir.c 2.2 KB

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