readdir.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright (C) 1991,92,93,94,95,96,97,99,2000 Free Software Foundation, Inc.
  4. * Copyright © 2018 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  5. *
  6. * This file is part of GNU Mes.
  7. *
  8. * GNU Mes is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or (at
  11. * your option) any later version.
  12. *
  13. * GNU Mes is distributed in the hope that it will be useful, but
  14. * WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. // Taken from GNU C Library 2.2.5
  22. #include <errno.h>
  23. #include <limits.h>
  24. #include <stddef.h>
  25. #include <string.h>
  26. #include <dirent.h>
  27. #include <unistd.h>
  28. #include <sys/types.h>
  29. #include <assert.h>
  30. #include <dirstream.h>
  31. int getdents (int filedes, char *buffer, size_t nbytes);
  32. /* Read a directory entry from DIRP. */
  33. struct dirent *
  34. readdir (DIR * dirp)
  35. {
  36. struct dirent *dp;
  37. int saved_errno = errno;
  38. do
  39. {
  40. size_t reclen;
  41. if (dirp->offset >= dirp->size)
  42. {
  43. /* We've emptied out our buffer. Refill it. */
  44. size_t maxread;
  45. ssize_t bytes;
  46. maxread = dirp->allocation;
  47. #if 0
  48. off_t base;
  49. bytes = __getdirentries (dirp->fd, dirp->data, maxread, &base);
  50. #else
  51. bytes = getdents (dirp->fd, dirp->data, maxread);
  52. #endif
  53. if (bytes <= 0)
  54. {
  55. /* Don't modifiy errno when reaching EOF. */
  56. if (bytes == 0)
  57. errno = saved_errno;
  58. dp = 0;
  59. break;
  60. }
  61. dirp->size = (size_t) bytes;
  62. /* Reset the offset into the buffer. */
  63. dirp->offset = 0;
  64. }
  65. dp = (struct dirent *) &dirp->data[dirp->offset];
  66. reclen = dp->d_reclen;
  67. dirp->offset += reclen;
  68. dirp->filepos = dp->d_off;
  69. /* Skip deleted files. */
  70. }
  71. while (dp->d_ino == 0);
  72. return dp;
  73. }