readdir_r.c 1.1 KB

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