readdir_r.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <errno.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <dirent.h>
  6. #include "dirstream.h"
  7. int readdir_r(DIR *dir, struct dirent *entry, struct dirent **result)
  8. {
  9. int ret;
  10. ssize_t bytes;
  11. struct dirent *de;
  12. if (!dir) {
  13. __set_errno(EBADF);
  14. return(EBADF);
  15. }
  16. de = NULL;
  17. __pthread_mutex_lock(&(dir->dd_lock));
  18. do {
  19. if (dir->dd_size <= dir->dd_nextloc) {
  20. /* read dir->dd_max bytes of directory entries. */
  21. bytes = __getdents(dir->dd_fd, dir->dd_buf, dir->dd_max);
  22. if (bytes <= 0) {
  23. *result = NULL;
  24. ret = errno;
  25. goto all_done;
  26. }
  27. dir->dd_size = bytes;
  28. dir->dd_nextloc = 0;
  29. }
  30. de = (struct dirent *) (((char *) dir->dd_buf) + dir->dd_nextloc);
  31. /* Am I right? H.J. */
  32. dir->dd_nextloc += de->d_reclen;
  33. /* We have to save the next offset here. */
  34. dir->dd_nextoff = de->d_off;
  35. /* Skip deleted files. */
  36. } while (de->d_ino == 0);
  37. if (de == NULL) {
  38. *result = NULL;
  39. } else {
  40. *result = __memcpy (entry, de, de->d_reclen);
  41. }
  42. ret = 0;
  43. all_done:
  44. __pthread_mutex_unlock(&(dir->dd_lock));
  45. return((de != NULL)? 0 : ret);
  46. }