1 /*
2 * Copyright 2005-2006 Vasil Dimov
3 * All rights reserved
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted providing that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 * POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 #include <sys/cdefs.h>
28
29 #include <err.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sysexits.h>
34
35 #include "exhaust_fp.h"
36
37 void
exhaust_fp(FILE * fp,void (* process)(char *,void *),void * process_arg)38 exhaust_fp(FILE *fp, void (*process)(char *, void *), void *process_arg)
39 {
40 char *buf;
41 size_t bufsz = BUFSIZ; /* start with some reasonable size */
42 size_t bufofft = 0;
43 size_t buflen;
44
45 if ((buf = (char *)malloc(bufsz)) == NULL)
46 err(EX_OSERR, "malloc(): %u", (unsigned)bufsz);
47
48 while (fgets(buf + bufofft, bufsz - bufofft, fp) != NULL)
49 {
50 buflen = strlen(buf);
51 if (buf[buflen - 1] != '\n')
52 {
53 bufsz *= 2;
54 if ((buf = realloc(buf, bufsz)) == NULL)
55 err(EX_OSERR, "realloc(): %u", (unsigned)bufsz);
56 bufofft = buflen;
57 continue;
58 }
59
60 /* remove trailing newline */
61 buf[buflen - 1] = '\0';
62
63 process(buf, process_arg);
64
65 bufofft = 0;
66 }
67
68 if (ferror(fp))
69 errx(EX_IOERR, "ferror()");
70
71 free(buf);
72 }
73
74 /* EOF */
75