fix errno value when fdopendir is given an invalid file descriptor
[musl] / src / dirent / fdopendir.c
1 #include <dirent.h>
2 #include <fcntl.h>
3 #include <sys/stat.h>
4 #include <errno.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <limits.h>
8 #include "__dirent.h"
9
10 DIR *fdopendir(int fd)
11 {
12         DIR *dir;
13         struct stat st;
14
15         if (fstat(fd, &st) < 0) {
16                 return 0;
17         }
18         if (!S_ISDIR(st.st_mode)) {
19                 errno = ENOTDIR;
20                 return 0;
21         }
22         if (!(dir = calloc(1, sizeof *dir))) {
23                 return 0;
24         }
25
26         fcntl(fd, F_SETFD, FD_CLOEXEC);
27         dir->fd = fd;
28         return dir;
29 }