scandir.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 <stdio.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <sys/types.h>
  26. #include "dirstream.h"
  27. /*
  28. * FIXME: This is a simple hack version which doesn't sort the data, and
  29. * just passes all unsorted.
  30. */
  31. int scandir(const char *dir, struct dirent ***namelist,
  32. int (*selector) (const struct dirent *),
  33. int (*compar) (const __ptr_t, const __ptr_t))
  34. {
  35. DIR *d = opendir(dir);
  36. struct dirent *current;
  37. struct dirent **names;
  38. int count = 0;
  39. int pos = 0;
  40. int result = -1;
  41. if (NULL == d)
  42. return -1;
  43. while (NULL != readdir(d))
  44. count++;
  45. names = malloc(sizeof (struct dirent *) * count);
  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. names = realloc(names, sizeof (struct dirent *) * pos);
  58. if (compar != NULL) {
  59. qsort(names, pos, sizeof (struct dirent *), compar);
  60. }
  61. *namelist = names;
  62. return pos;
  63. }