• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "stdio_impl.h"
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <limits.h>
7 
fopen(const char * restrict filename,const char * restrict mode)8 FILE *fopen(const char *restrict filename, const char *restrict mode)
9 {
10 	FILE *f;
11 	int fd;
12 	int flags;
13 
14 	/* Check for valid initial mode character */
15 	if (!strchr("rwa", *mode)) {
16 		errno = EINVAL;
17 		return 0;
18 	}
19 
20 	/* Compute the flags to pass to open() */
21 	flags = __fmodeflags(mode);
22 
23 	fd = open(filename, flags, 0666);
24 	if (fd < 0) return 0;
25 	if (flags & O_CLOEXEC)
26 		fcntl(fd, F_SETFD, FD_CLOEXEC);
27 
28 #if !defined(__LP64__)
29 	if (fd > SHRT_MAX) {
30 		errno = EMFILE;
31 		return 0;
32 	}
33 #endif
34 
35 	f = __fdopen(fd, mode);
36 	if (f) return f;
37 
38 	close(fd);
39 	return 0;
40 }
41 
42 weak_alias(fopen, fopen64);
43