summaryrefslogtreecommitdiff
path: root/user/lib/fread.c
blob: f8d0ad8397de8d5d6aaf9c06a5e4152de9043630 (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
63
64
65
#include <stdio.h>
#include <unistd.h>

FILE *stdin = (void *)0;

int getchar(void)
{
	return fgetc(stdin);
}

int getc(FILE *stream)
{
	return fgetc(stream);
}

int fgetc(FILE *stream)
{
	int c;
	if (fread(&c, 1, 1, stream) < 1)
		return EOF;
	return c;
}

char *gets(char *str)
{
	char *s = str;
	while (1) {
		char c = fgetc(stdin);
		if (c == '\n' || c == EOF || c == '\0')
			break;
		*(str++) = c;
	}
	*str = '\0';
	return s;
}

char *fgets(char *restrict str, int size, FILE *stream)
{
	if (size < 1)
		return NULL;

	char *s = str;
	while (size > 1) {
		char c = fgetc(stream);
		if (c == '\n' || c == EOF || c == '\0')
			break;
		*(str++) = c;
		size--;
	}

	*str = '\0';
	return s;
}

size_t fread(void *restrict ptr, size_t size, size_t n, FILE *restrict stream)
{
	int fd = (uintptr_t)stream;
	char *restrict buf = ptr;

	for (size_t i = 0; i < n; i++)
		if (read(fd, buf + i * size, size) < 1)
			return i;

	return n;
}