opendir.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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_fd = fd;
  37. ptr->dd_nextloc = ptr->dd_size = ptr->dd_nextoff = 0;
  38. ptr->dd_getdents = unknown;
  39. ptr->dd_max = statbuf.st_blksize;
  40. if (ptr->dd_max < 512)
  41. ptr->dd_max = 512;
  42. if (!(buf = calloc(1, ptr->dd_max))) {
  43. close(fd);
  44. free(ptr);
  45. __set_errno(ENOMEM);
  46. return NULL;
  47. }
  48. ptr->dd_buf = buf;
  49. return ptr;
  50. }