summaryrefslogtreecommitdiff
path: root/lib/libc/stdio/fmemopen.c
blob: 21e811fde314d1f40976c7ca774e7eaad22ebe5f (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
#include "__stdio.h"  // for __libc_fadd
#include "features.h" // for __weak
#include "stddef.h"   // for NULL

#include <errno.h>  // for EINVAL, errno
#include <fcntl.h>  // for O_WRONLY, O_CREAT, O_RDONLY, O_APPEND, O_RDWR
#include <libc.h>   // for __IMPL
#include <stdio.h>  // for FILE, _IOFBF, fmemopen, size_t
#include <stdlib.h> // for calloc, free
#include <string.h> // for strchr

__weak void __stdio_cleanup(void)
{
}

FILE *fmemopen(void *restrict buf, size_t max_size, const char *restrict mode)
{
	int flags;
	FILE *stream = calloc(1, sizeof(FILE));

	if (stream == NULL)
		return stream;

	__IMPL(stream)->fd = -1;
	__IMPL(stream)->buf = buf;
	__IMPL(stream)->buf_size = max_size;
	__IMPL(stream)->type = _IOFBF;

	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;
	} else {
		free(stream);
		errno = EINVAL;
		return NULL;
	}

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

	__IMPL(stream)->flags = flags;

	__libc_fadd(stream);

	return stream;
}