xref: /illumos-gate/usr/src/cmd/mailwrapper/fgetln.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /* $Id$ */
2 /*	$NetBSD: fgetln.c,v 1.3 2007/08/07 02:06:58 lukem Exp $	*/
3 
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Christos Zoulas.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of The NetBSD Foundation nor the names of its
20  *    contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include <sys/types.h>
37 
38 #include <errno.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 
43 char *
44 fgetln(FILE *fp, size_t *len)
45 {
46 	static char *buf = NULL;
47 	static size_t bufsiz = 0;
48 	char *ptr;
49 
50 
51 	if (buf == NULL) {
52 		bufsiz = BUFSIZ;
53 		if ((buf = malloc(bufsiz)) == NULL)
54 			return (NULL);
55 	}
56 
57 	if (fgets(buf, bufsiz, fp) == NULL)
58 		return (NULL);
59 
60 	*len = 0;
61 	while ((ptr = strchr(&buf[*len], '\n')) == NULL) {
62 		size_t nbufsiz = bufsiz + BUFSIZ;
63 		char *nbuf = realloc(buf, nbufsiz);
64 
65 		if (nbuf == NULL) {
66 			int oerrno = errno;
67 			free(buf);
68 			errno = oerrno;
69 			buf = NULL;
70 			return (NULL);
71 		} else
72 			buf = nbuf;
73 
74 		*len = bufsiz;
75 		if (fgets(&buf[bufsiz], BUFSIZ, fp) == NULL)
76 			return (buf);
77 
78 		bufsiz = nbufsiz;
79 	}
80 
81 	*len = (ptr - buf) + 1;
82 	return (buf);
83 }
84