scandir.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. 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. if (selector == NULL || (*selector) (current))
  34. {
  35. struct dirent *vnew;
  36. size_t dsize;
  37. /* Ignore errors from selector or readdir */
  38. __set_errno (0);
  39. if (unlikely(pos == names_size))
  40. {
  41. struct dirent **new;
  42. if (names_size == 0)
  43. names_size = 10;
  44. else
  45. names_size *= 2;
  46. new = (struct dirent **) realloc (names, names_size * sizeof (struct dirent *));
  47. if (new == NULL)
  48. break;
  49. names = new;
  50. }
  51. dsize = &current->d_name[_D_ALLOC_NAMLEN (current)] - (char *) current;
  52. vnew = (struct dirent *) malloc (dsize);
  53. if (vnew == NULL)
  54. break;
  55. names[pos++] = (struct dirent *) memcpy (vnew, current, dsize);
  56. }
  57. if (unlikely(errno != 0))
  58. {
  59. save = errno;
  60. closedir (dp);
  61. while (pos > 0)
  62. free (names[--pos]);
  63. free (names);
  64. __set_errno (save);
  65. return -1;
  66. }
  67. closedir (dp);
  68. __set_errno (save);
  69. /* Sort the list if we have a comparison function to sort with. */
  70. if (compar != NULL)
  71. qsort (names, pos, sizeof (struct dirent *), compar);
  72. *namelist = names;
  73. return pos;
  74. }