xref: /netbsd-src/tools/compat/fgetln.c (revision ccd9df534e375a4366c5b55f23782053c7a98d82)
1 /*	$NetBSD: fgetln.c,v 1.12 2015/10/09 14:42:40 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2015 Joerg Jung <jung@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * portable fgetln() version
21  */
22 
23 #ifdef HAVE_NBTOOL_CONFIG_H
24 #include "nbtool_config.h"
25 #endif
26 
27 #if !HAVE_FGETLN
28 #include <stdlib.h>
29 #ifndef HAVE_NBTOOL_CONFIG_H
30 /* These headers are required, but included from nbtool_config.h */
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <errno.h>
34 #endif
35 
36 char *
37 fgetln(FILE *fp, size_t *len)
38 {
39 	static char *buf = NULL;
40 	static size_t bufsz = 0;
41 	size_t r = 0;
42 	char *p;
43 	int c, e;
44 
45 	if (!fp || !len) {
46 		errno = EINVAL;
47 		return NULL;
48 	}
49 	if (!buf) {
50 		if (!(buf = calloc(1, BUFSIZ)))
51 			return NULL;
52 		bufsz = BUFSIZ;
53 	}
54 	while ((c = getc(fp)) != EOF) {
55 		buf[r++] = c;
56 		if (r == bufsz) {
57 			/*
58 			 * Original uses reallocarray() but we don't have it
59 			 * in tools.
60 			 */
61 			if (!(p = realloc(buf, 2 * bufsz))) {
62 				e = errno;
63 				free(buf);
64 				errno = e;
65 				buf = NULL, bufsz = 0;
66 				return NULL;
67 			}
68 			buf = p, bufsz = 2 * bufsz;
69 		}
70 		if (c == '\n')
71 			break;
72 	}
73 	return (*len = r) ? buf : NULL;
74 }
75 #endif
76 
77 
78 #ifdef TEST
79 int
80 main(int argc, char *argv[])
81 {
82 	char *p;
83 	size_t len;
84 
85 	while ((p = fgetln(stdin, &len)) != NULL) {
86 		(void)printf("%zu %s", len, p);
87 		free(p);
88 	}
89 	return 0;
90 }
91 #endif
92