scandir.c 2.1 KB

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