fgetln.c revision 1.1 1 /* $NetBSD: fgetln.c,v 1.1 2002/01/04 14:39:07 lukem Exp $ */
2
3 /*
4 * Copyright 1999 Luke Mewburn <lukem (at) 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 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #ifndef HAVE_FGETLN
35
36 #define BUFCHUNKS BUFSIZ
37
38 char *
39 fgetln(FILE *fp, size_t *len)
40 {
41 static char *buf;
42 static size_t bufsize;
43 size_t buflen;
44 char curbuf[BUFCHUNKS];
45 char *p;
46
47 if (buf == NULL) {
48 bufsize = BUFCHUNKS;
49 buf = (char *)malloc(bufsize);
50 if (buf == NULL)
51 err(1, "Unable to allocate buffer for fgetln()");
52 }
53
54 *buf = '\0';
55 buflen = 0;
56 while ((p = fgets(curbuf, sizeof(curbuf), fp)) != NULL) {
57 size_t l;
58
59 l = strlen(p);
60 if (bufsize < buflen + l) {
61 bufsize += BUFCHUNKS;
62 if ((buf = (char *)realloc(buf, bufsize)) == NULL)
63 err(1, "Unable to allocate %ld bytes of memory",
64 (long)bufsize);
65 }
66 strcpy(buf + buflen, p);
67 buflen += l;
68 if (p[l - 1] == '\n')
69 break;
70 }
71 if (p == NULL && *buf == '\0')
72 return (NULL);
73 *len = strlen(buf);
74 return (buf);
75 }
76 #endif /* HAVE_FGETLN */
77