scandir.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (C) 2000-2006 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 <stdio.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <errno.h>
  11. #include <sys/types.h>
  12. #include "dirstream.h"
  13. int scandir(const char *dir, struct dirent ***namelist,
  14. int (*selector) (const struct dirent *),
  15. int (*compar) (const struct dirent **, const struct dirent **))
  16. {
  17. DIR *dp = opendir (dir);
  18. struct dirent *current;
  19. struct dirent **names = NULL;
  20. size_t names_size = 0, pos;
  21. int save;
  22. if (dp == NULL)
  23. return -1;
  24. save = errno;
  25. __set_errno (0);
  26. pos = 0;
  27. while ((current = readdir (dp)) != NULL) {
  28. int use_it = selector == NULL;
  29. if (! use_it)
  30. {
  31. use_it = (*selector) (current);
  32. /* The selector function might have changed errno.
  33. * It was zero before and it need to be again to make
  34. * the latter tests work. */
  35. if (! use_it)
  36. __set_errno (0);
  37. }
  38. if (use_it)
  39. {
  40. struct dirent *vnew;
  41. size_t dsize;
  42. /* Ignore errors from selector or readdir */
  43. __set_errno (0);
  44. if (unlikely(pos == names_size))
  45. {
  46. struct dirent **new;
  47. if (names_size == 0)
  48. names_size = 10;
  49. else
  50. names_size *= 2;
  51. new = (struct dirent **) realloc (names,
  52. names_size * sizeof (struct dirent *));
  53. if (new == NULL)
  54. break;
  55. names = new;
  56. }
  57. dsize = &current->d_name[_D_ALLOC_NAMLEN(current)] - (char*)current;
  58. vnew = (struct dirent *) malloc (dsize);
  59. if (vnew == NULL)
  60. break;
  61. names[pos++] = (struct dirent *) memcpy (vnew, current, dsize);
  62. }
  63. }
  64. if (unlikely(errno != 0))
  65. {
  66. save = errno;
  67. closedir (dp);
  68. while (pos > 0)
  69. free (names[--pos]);
  70. free (names);
  71. __set_errno (save);
  72. return -1;
  73. }
  74. closedir (dp);
  75. __set_errno (save);
  76. /* Sort the list if we have a comparison function to sort with. */
  77. if (compar != NULL)
  78. qsort (names, pos, sizeof (struct dirent *), (comparison_fn_t) compar);
  79. *namelist = names;
  80. return pos;
  81. }