summaryrefslogtreecommitdiff
path: root/libobj/getline.c
blob: 5acdf8d1c4cb43e0a458c174d5a6e94b7e592a3b (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
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

extern int getline(char **line, size_t *len, FILE *file);

int getline(char **line, size_t *len, FILE *file)
{
	char *ptr, *end;
	int c;

	if (*line == NULL) {
		errno = EINVAL;
		if (*len == 0)
			*line = malloc(4096);
		if (*line == NULL)
			return -1;

		*len = 4096;
	}

	ptr = *line;
	end = *line + *len;

	while ((c = fgetc(file)) != EOF) {
		if (ptr + 1 >= end) {
			char *newline;
			int offset;

			newline = realloc(*line, *len + 4096);
			if (newline == NULL)
				return -1;

			offset = ptr - *line;

			*line = newline;
			*len += 4096;

			ptr = *line + offset;
			end = *line + *len;
		}

		*ptr++ = c;
		if (c == '\n') {
			*ptr = '\0';
			return ptr - *line;
		}
	}
	*ptr = '\0';
	return -1;
}