initial check-in, version 0.5.0
[musl] / src / stdio / fopen.c
1 #include "stdio_impl.h"
2
3 FILE *fopen(const char *filename, const char *mode)
4 {
5         FILE *f;
6         int fd;
7         int flags;
8         int plus = !!strchr(mode, '+');
9
10         /* Check for valid initial mode character */
11         if (!strchr("rwa", *mode)) {
12                 errno = EINVAL;
13                 return 0;
14         }
15
16         /* Compute the flags to pass to open() */
17         if (plus) flags = O_RDWR;
18         else if (*mode == 'r') flags = O_RDONLY;
19         else flags = O_WRONLY;
20         if (*mode != 'r') flags |= O_CREAT;
21         if (*mode == 'w') flags |= O_TRUNC;
22         if (*mode == 'a') flags |= O_APPEND;
23
24         fd = __syscall_open(filename, flags, 0666);
25         if (fd < 0) return 0;
26
27         f = __fdopen(fd, mode);
28         if (f) return f;
29
30         __syscall_close(fd);
31         return 0;
32 }
33
34 LFS64(fopen);