summaryrefslogtreecommitdiff
path: root/examples/hello_strlcpy/getline.c
blob: 777f5c46b1736ec4521489537737a836f458015b (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
/*
 * Copyright (c) 2007-2013 by Aleksey Cheusov
 *
 * See LICENSE file in the distribution.
 */

#include <stdio.h>
#include <stdlib.h>

#include "decls.h"

ssize_t
getline(char** lineptr, size_t* n, FILE* stream)
{
	int c;
	size_t sz = 0;

	while (c = getc (stream), c != EOF){
		if (sz+1 >= *n){
			/* +2 is for `c' and 0-terminator */
			*n = *n * 3 / 2 + 2;
			*lineptr = realloc (*lineptr, *n);
			if (!*lineptr)
				return -1;
		}

		(*lineptr) [sz++] = (char) c;
		if (c == '\n')
			break;
	}

	if (ferror (stdin))
		return (ssize_t) -1;

	if (!sz){
		if (feof (stdin)){
			return (ssize_t) -1;
		}else if (!*n){
			*lineptr = malloc (1);
			if (!*lineptr)
				return -1;

			*n = 1;
		}
	}

	(*lineptr) [sz] = 0;
	return sz;
}