2a20c7f2869d97d368369ac291ae7832e3fbbaa6
[musl] / src / stdio / fopen.c
1 #include "stdio_impl.h"
2 #include <fcntl.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "libc.h"
6
7 FILE *fopen(const char *restrict filename, const char *restrict mode)
8 {
9         FILE *f;
10         int fd;
11         int flags;
12
13         /* Check for valid initial mode character */
14         if (!strchr("rwa", *mode)) {
15                 errno = EINVAL;
16                 return 0;
17         }
18
19         /* Compute the flags to pass to open() */
20         flags = __fmodeflags(mode);
21
22         fd = sys_open(filename, flags, 0666);
23         if (fd < 0) return 0;
24         if (flags & O_CLOEXEC)
25                 __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
26
27         f = __fdopen(fd, mode);
28         if (f) return f;
29
30         __syscall(SYS_close, fd);
31         return 0;
32 }
33
34 LFS64(fopen);