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