home *** CD-ROM | disk | FTP | other *** search
/ Serving the Web / ServingTheWeb1995.disc1of1.iso / linux / slacksrce / d / libc / libc-4.6 / libc-4 / libc-linux / dirent / opendir.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-08  |  1.2 KB  |  57 lines

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