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