summaryrefslogtreecommitdiff
path: root/lib/libc/stdio/fopen.c
blob: 5415e711968c27a47b09d3ccafa4b86976eabf74 (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
60
61
62
#include <__stdio.h>

#include <errno.h>  // for EINVAL, errno
#include <fcntl.h>  // for O_WRONLY, O_CREAT, O_RDONLY, open, O_APPEND
#include <stdio.h>  // for FILE, BUFSIZ, fopen, _IOLBF
#include <stdlib.h> // for calloc, free, malloc
#include <string.h> // for strchr
#include <sys/cdefs.h>
#include <unistd.h> // for close

__weak void __stdio_cleanup(void)
{
}

FILE *fopen(const char *restrict pathname, const char *restrict mode)
{
	int fd, flags, _mode;
	FILE *stream;

	_mode = 0;
	if (mode[0] == 'r') {
		flags = O_RDONLY;
	} else if (mode[0] == 'w') {
		flags = O_WRONLY | O_CREAT | O_TRUNC;
	} else if (mode[0] == 'a') {
		flags = O_WRONLY | O_CREAT | O_APPEND;
		_mode = 0666;
	} else {
		errno = EINVAL;
		return NULL;
	}

	if (strchr(mode, '+')) {
		flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
	}

	fd = open(pathname, flags, _mode);
	if (fd < 0)
		return NULL;

	stream = calloc(1, sizeof(struct __FILE));
	if (stream == NULL)
		return NULL;

	__FILE(stream)->fd = fd;
	__FILE(stream)->buf_size = BUFSIZ;
	__FILE(stream)->flags = flags;
	__FILE(stream)->type = _IOLBF;
	atomic_flag_clear(&__FILE(stream)->lock);

	__FILE(stream)->buf = malloc(BUFSIZ);

	if (__FILE(stream)->buf == NULL) {
		close(fd);
		free(stream);
		return NULL;
	}

	__libc_fadd(stream);

	return stream;
}