fgetln.c revision 1.10 1 /* $NetBSD: fgetln.c,v 1.10 2015/10/08 20:20:45 christos Exp $ */
2
3 /*
4 * Copyright (c) 2015 Joerg Jung <jung (at) 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, reentrant
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 // Original uses reallocarray() but we don't have it
58 // in tools.
59 if (!(p = realloc(buf, 2 * bufsz))) {
60 e = errno;
61 free(buf);
62 errno = e;
63 buf = NULL, bufsz = 0;
64 return NULL;
65 }
66 buf = p, bufsz = 2 * bufsz;
67 }
68 if (c == '\n')
69 break;
70 }
71 return (*len = r) ? buf : NULL;
72 }
73 #endif
74
75
76 #ifdef TEST
77 int
78 main(int argc, char *argv[])
79 {
80 char *p;
81 size_t len;
82
83 while ((p = fgetln(stdin, &len)) != NULL) {
84 (void)printf("%zu %s", len, p);
85 free(p);
86 }
87 return 0;
88 }
89 #endif
90