2 a81bb85a 2026-02-19 martijn * Copyright (c) 2015 Joerg Jung <jung@openbsd.org>
4 a81bb85a 2026-02-19 martijn * Permission to use, copy, modify, and distribute this software for any
5 a81bb85a 2026-02-19 martijn * purpose with or without fee is hereby granted, provided that the above
6 a81bb85a 2026-02-19 martijn * copyright notice and this permission notice appear in all copies.
8 a81bb85a 2026-02-19 martijn * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 a81bb85a 2026-02-19 martijn * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 a81bb85a 2026-02-19 martijn * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 a81bb85a 2026-02-19 martijn * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 a81bb85a 2026-02-19 martijn * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 a81bb85a 2026-02-19 martijn * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 a81bb85a 2026-02-19 martijn * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 a81bb85a 2026-02-19 martijn * portable fgetln() version, NOT reentrant
21 a81bb85a 2026-02-19 martijn #include <stdio.h>
22 a81bb85a 2026-02-19 martijn #include <stdlib.h>
23 a81bb85a 2026-02-19 martijn #include <errno.h>
25 a81bb85a 2026-02-19 martijn #include "compat.h"
28 a81bb85a 2026-02-19 martijn fgetln(FILE *fp, size_t *len)
30 a81bb85a 2026-02-19 martijn static char *buf = NULL;
31 a81bb85a 2026-02-19 martijn static size_t bufsz = 0;
32 a81bb85a 2026-02-19 martijn size_t r = 0;
34 a81bb85a 2026-02-19 martijn int c, e;
36 a81bb85a 2026-02-19 martijn if (!fp || !len) {
37 a81bb85a 2026-02-19 martijn errno = EINVAL;
38 a81bb85a 2026-02-19 martijn return NULL;
40 a81bb85a 2026-02-19 martijn if (!buf) {
41 a81bb85a 2026-02-19 martijn if (!(buf = calloc(1, BUFSIZ)))
42 a81bb85a 2026-02-19 martijn return NULL;
43 a81bb85a 2026-02-19 martijn bufsz = BUFSIZ;
45 a81bb85a 2026-02-19 martijn while ((c = getc(fp)) != EOF) {
46 a81bb85a 2026-02-19 martijn buf[r++] = c;
47 a81bb85a 2026-02-19 martijn if (r == bufsz) {
48 a81bb85a 2026-02-19 martijn if (!(p = reallocarray(buf, 2, bufsz))) {
49 a81bb85a 2026-02-19 martijn e = errno;
50 a81bb85a 2026-02-19 martijn free(buf);
51 a81bb85a 2026-02-19 martijn errno = e;
52 a81bb85a 2026-02-19 martijn buf = NULL, bufsz = 0;
53 a81bb85a 2026-02-19 martijn return NULL;
55 a81bb85a 2026-02-19 martijn buf = p, bufsz = 2 * bufsz;
57 a81bb85a 2026-02-19 martijn if (c == '\n')
60 a81bb85a 2026-02-19 martijn return (*len = r) ? buf : NULL;