opendir.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <errno.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <sys/dir.h>
  7. #include <sys/stat.h>
  8. #include "dirstream.h"
  9. /* opendir just makes an open() call - it return NULL if it fails
  10. * (open sets errno), otherwise it returns a DIR * pointer.
  11. */
  12. DIR *opendir(const char *name)
  13. {
  14. int fd;
  15. struct stat statbuf;
  16. char *buf;
  17. DIR *ptr;
  18. if (stat(name, &statbuf))
  19. return NULL;
  20. if (!S_ISDIR(statbuf.st_mode)) {
  21. __set_errno(ENOTDIR);
  22. return NULL;
  23. }
  24. if ((fd = open(name, O_RDONLY)) < 0)
  25. return NULL;
  26. /* According to POSIX, directory streams should be closed when
  27. * exec. From "Anna Pluzhnikov" <besp@midway.uchicago.edu>.
  28. */
  29. if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
  30. return NULL;
  31. if (!(ptr = malloc(sizeof(*ptr)))) {
  32. close(fd);
  33. __set_errno(ENOMEM);
  34. return NULL;
  35. }
  36. ptr->dd_max = statbuf.st_blksize;
  37. if (ptr->dd_max < 512)
  38. ptr->dd_max = 512;
  39. if (!(buf = malloc(ptr->dd_max))) {
  40. close(fd);
  41. free(ptr);
  42. __set_errno(ENOMEM);
  43. return NULL;
  44. }
  45. ptr->dd_fd = fd;
  46. ptr->dd_nextoff = ptr->dd_nextloc = ptr->dd_size = 0;
  47. ptr->dd_buf = buf;
  48. ptr->dd_getdents = unknown;
  49. return ptr;
  50. }