readdir_r.c 1.2 KB

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