1268
|
1 /* line.c: return the next line from a file, or NULL. |
|
2 |
|
3 Copyright (C) 1992, 93 Free Software Foundation, Inc. |
|
4 |
|
5 This program is free software; you can redistribute it and/or modify |
|
6 it under the terms of the GNU General Public License as published by |
|
7 the Free Software Foundation; either version 2, or (at your option) |
|
8 any later version. |
|
9 |
|
10 This program is distributed in the hope that it will be useful, |
|
11 but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13 GNU General Public License for more details. |
|
14 |
|
15 You should have received a copy of the GNU General Public License |
|
16 along with this program; if not, write to the Free Software |
1315
|
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ |
1268
|
18 |
|
19 /* Don't include config.h or all our other usual includes, since |
|
20 it's useful to just throw this file into other programs. */ |
|
21 |
|
22 #include <stdio.h> |
|
23 extern void free (); |
|
24 |
|
25 /* From xmalloc.c and xrealloc.c. This saves having to include config.h. */ |
|
26 extern void *xmalloc (), *xrealloc (); |
|
27 |
|
28 |
|
29 /* Allocate in increments of this size. */ |
|
30 #define BLOCK_SIZE 40 |
|
31 |
|
32 char * |
|
33 read_line (f) |
|
34 FILE *f; |
|
35 { |
|
36 int c; |
|
37 unsigned limit = BLOCK_SIZE; |
|
38 unsigned loc = 0; |
|
39 char *line = xmalloc (limit); |
|
40 |
|
41 while ((c = getc (f)) != EOF && c != '\n') |
|
42 { |
|
43 line[loc] = c; |
|
44 loc++; |
|
45 |
|
46 /* By testing after the assignment, we guarantee that we'll always |
|
47 have space for the null we append below. We know we always |
|
48 have room for the first char, since we start with BLOCK_SIZE. */ |
|
49 if (loc == limit) |
|
50 { |
|
51 limit += BLOCK_SIZE; |
|
52 line = xrealloc (line, limit); |
|
53 } |
|
54 } |
|
55 |
|
56 /* If we read anything, return it. This can't represent a last |
|
57 ``line'' which doesn't end in a newline, but so what. */ |
|
58 if (c != EOF) |
|
59 { |
|
60 /* Terminate the string. We can't represent nulls in the file, |
|
61 either. Again, it doesn't matter. */ |
|
62 line[loc] = 0; |
|
63 } |
|
64 else /* At end of file. */ |
|
65 { |
|
66 free (line); |
|
67 line = NULL; |
|
68 } |
|
69 |
|
70 return line; |
|
71 } |