scandir.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* -*- Mode: C; c-file-style: "gnu" -*- */
  2. /*
  3. Copyright (c) 2000 Petter Reinholdtsen
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use, copy,
  8. modify, merge, publish, distribute, sublicense, and/or sell copies
  9. of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. */
  22. #include <dirent.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <stdlib.h>
  26. #include <sys/types.h>
  27. #include "dirstream.h"
  28. int scandir(const char *dir, struct dirent ***namelist,
  29. int (*selector) (const struct dirent *),
  30. int (*compar) (const __ptr_t, const __ptr_t))
  31. {
  32. DIR *d = opendir(dir);
  33. struct dirent *current;
  34. struct dirent **names;
  35. int count = 0;
  36. int pos = 0;
  37. int result = -1;
  38. if (NULL == d)
  39. return -1;
  40. while (NULL != readdir(d))
  41. count++;
  42. if (!(names = malloc(sizeof (struct dirent *) * count))) {
  43. closedir(d);
  44. return -1;
  45. }
  46. rewinddir(d);
  47. while (NULL != (current = readdir(d))) {
  48. if (NULL == selector || selector(current)) {
  49. struct dirent *copyentry = malloc(current->d_reclen);
  50. memcpy(copyentry, current, current->d_reclen);
  51. names[pos] = copyentry;
  52. pos++;
  53. }
  54. }
  55. result = closedir(d);
  56. if (pos != count) {
  57. struct dirent **tmp;
  58. if (!(tmp = realloc(names, sizeof (struct dirent *) * pos))) {
  59. free(names);
  60. return -1;
  61. }
  62. names = tmp;
  63. }
  64. if (compar != NULL) {
  65. qsort(names, pos, sizeof (struct dirent *), compar);
  66. }
  67. *namelist = names;
  68. return pos;
  69. }