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