main netmisc / compat / fgetln.c
 1/*	$NetBSD: fgetln.c,v 1.5 2003/10/27 00:12:43 lukem Exp $	*/
 2
 3/*
 4 * Copyright 1999 Luke Mewburn <lukem@NetBSD.org>.
 5 * All rights reserved.
 6 *
 7 * Redistribution and use in source and binary forms, with or without
 8 * modification, are permitted provided that the following conditions
 9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 *    derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include "nbtool_config.h"
31
32#if !HAVE_FGETLN
33#include <err.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37
38#define BUFCHUNKS	BUFSIZ
39
40char *
41fgetln(FILE *fp, size_t *len)
42{
43	static char *buf;
44	static size_t bufsize;
45	size_t buflen;
46	char curbuf[BUFCHUNKS];
47	char *p;
48
49	if (buf == NULL) {
50		bufsize = BUFCHUNKS;
51		buf = (char *)malloc(bufsize);
52		if (buf == NULL)
53			err(1, "Unable to allocate buffer for fgetln()");
54	}
55
56	*buf = '\0';
57	buflen = 0;
58	while ((p = fgets(curbuf, sizeof(curbuf), fp)) != NULL) {
59		size_t l;
60
61		l = strlen(p);
62		if (bufsize < buflen + l) {
63			bufsize += BUFCHUNKS;
64			if ((buf = (char *)realloc(buf, bufsize)) == NULL)
65				err(1, "Unable to allocate %ld bytes of memory",
66				    (long)bufsize);
67		}
68		strcpy(buf + buflen, p);
69		buflen += l;
70		if (p[l - 1] == '\n')
71			break;
72	}
73	if (p == NULL && *buf == '\0')
74		return (NULL);
75	*len = strlen(buf);
76	return (buf);
77}
78#endif