readdir_r.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. extern int getdents __P ((unsigned int fd, struct dirent *dirp, unsigned int count));
  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. #ifdef _POSIX_THREADS
  19. pthread_mutex_lock(dir->dd_lock);
  20. #endif
  21. do {
  22. if (dir->dd_size <= dir->dd_nextloc) {
  23. /* read dir->dd_max bytes of directory entries. */
  24. bytes = getdents(dir->dd_fd, dir->dd_buf, dir->dd_max);
  25. if (bytes <= 0) {
  26. *result = NULL;
  27. ret = errno;
  28. goto all_done;
  29. }
  30. dir->dd_size = bytes;
  31. dir->dd_nextloc = 0;
  32. }
  33. de = (struct dirent *) (((char *) dir->dd_buf) + dir->dd_nextloc);
  34. /* Am I right? H.J. */
  35. dir->dd_nextloc += de->d_reclen;
  36. /* We have to save the next offset here. */
  37. dir->dd_nextoff = de->d_off;
  38. /* Skip deleted files. */
  39. } while (de->d_ino == 0);
  40. if (de == NULL) {
  41. *result = NULL;
  42. } else {
  43. *result = memcpy (entry, de, de->d_reclen);
  44. }
  45. ret = 0;
  46. all_done:
  47. #ifdef _POSIX_THREADS
  48. pthread_mutex_unlock(dir->dd_lock);
  49. #endif
  50. return((de != NULL)? 0 : ret);
  51. }