xref: /freebsd/contrib/mandoc/compat_getline.c (revision cddbc3b40812213ff00041f79174cac0be360a2a)
1 #include "config.h"
2 
3 #if HAVE_GETLINE
4 
5 int dummy;
6 
7 #else
8 
9 /*	$Id: compat_getline.c,v 1.1 2015/11/07 20:52:52 schwarze Exp $ */
10 /*
11  * Copyright (c) 2015 Ingo Schwarze <schwarze@openbsd.org>
12  *
13  * Permission to use, copy, modify, and distribute this software for any
14  * purpose with or without fee is hereby granted, provided that the above
15  * copyright notice and this permission notice appear in all copies.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
18  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
20  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
21  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
22  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
23  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  */
25 
26 #include <sys/types.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 
31 ssize_t
32 getline(char **buf, size_t *bufsz, FILE *fp)
33 {
34 	char	*nbuf;
35 	size_t	 nbufsz, pos;
36 	int	 c;
37 
38 	if (buf == NULL || bufsz == NULL) {
39 		errno = EINVAL;
40 		return -1;
41 	}
42 
43 	if (*buf == NULL)
44 		*bufsz = 0;
45 	else
46 		**buf = '\0';
47 
48 	pos = 0;
49 	for (;;) {
50 		if (pos + 1 >= *bufsz) {
51 			nbufsz = *bufsz ? *bufsz * 2 : BUFSIZ;
52 			if ((nbuf = realloc(*buf, nbufsz)) == NULL)
53 				return -1;
54 			*buf = nbuf;
55 			*bufsz = nbufsz;
56 		}
57 		if ((c = fgetc(fp)) == EOF) {
58 			(*buf)[pos] = '\0';
59 			return pos > 0 && feof(fp) ? (ssize_t)pos : -1;
60 		}
61 		(*buf)[pos++] = c;
62 		(*buf)[pos] = '\0';
63 		if (c == '\n')
64 			return pos;
65 	}
66 }
67 
68 #endif
69