summaryrefslogtreecommitdiffstats
path: root/usr/klibc/stdio/fopen.c
blob: cf098dfdd1dad083e6b25714ef88258a0214c7b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * fopen.c
 */

#include "stdioint.h"

static int __parse_open_mode(const char *mode)
{
	int rwflags = O_RDONLY;
	int crflags = 0;
	int eflags  = 0;

	while (*mode) {
		switch (*mode++) {
		case 'r':
			rwflags = O_RDONLY;
			crflags = 0;
			break;
		case 'w':
			rwflags = O_WRONLY;
			crflags = O_CREAT | O_TRUNC;
			break;
		case 'a':
			rwflags = O_WRONLY;
			crflags = O_CREAT | O_APPEND;
			break;
		case 'e':
			eflags |= O_CLOEXEC;
			break;
		case 'x':
			eflags |= O_EXCL;
			break;
		case '+':
			rwflags = O_RDWR;
			break;
		}
	}

	return rwflags | crflags | eflags;
}

FILE *fopen(const char *file, const char *mode)
{
	int flags = __parse_open_mode(mode);
	int fd, err;
	FILE *f;

	fd = open(file, flags, 0666);
	if (fd < 0)
		return NULL;

	f = fdopen(fd, mode);
	if (!f) {
		err = errno;
		close(fd);
		errno = err;
	}
	return f;
}