scandir.c 2.2 KB

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