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

#include <libc.h>   // for __IMPL
#include <stdio.h>  // for FILE, _IONBF, SEEK_END, _IOLBF, fdopen
#include <stdlib.h> // for calloc, free
#include <unistd.h> // for lseek, off_t

__weak void __stdio_cleanup(void)
{
}

FILE *fdopen(int fildes, const char *mode)
{
	FILE *stream;

	if (mode == NULL ||
	    (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a')) {
		return NULL;
	}

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

	__IMPL(stream)->fd = fildes;
	atomic_flag_clear(&__IMPL(stream)->lock);
	if (mode[0] == 'r') {
		__IMPL(stream)->type = _IONBF;
	} else if (mode[0] == 'w') {
		__IMPL(stream)->type = _IOLBF;
	} else if (mode[0] == 'a') {
		__IMPL(stream)->type = _IONBF;

		off_t offset = lseek(fildes, 0, SEEK_END);
		if (offset == (off_t)-1) {
			free(stream);
			return NULL;
		}
	}

	__libc_fadd(stream);
	return stream;
}