Include unlocked-io.h.
[gnulib.git] / lib / linebuffer.c
1 /* linebuffer.c -- read arbitrarily long lines
2    Copyright (C) 1986, 1991, 1998, 1999, 2001 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Richard Stallman. */
19 \f
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include "linebuffer.h"
27 #include "unlocked-io.h"
28
29 char *xmalloc ();
30 char *xrealloc ();
31 void free ();
32
33 /* Initialize linebuffer LINEBUFFER for use. */
34
35 void
36 initbuffer (struct linebuffer *linebuffer)
37 {
38   linebuffer->length = 0;
39   linebuffer->size = 200;
40   linebuffer->buffer = (char *) xmalloc (linebuffer->size);
41 }
42
43 /* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
44    Keep the newline; append a newline if it's the last line of a file
45    that ends in a non-newline character.  Do not null terminate.
46    Return LINEBUFFER, except at end of file return 0.  */
47
48 struct linebuffer *
49 readline (struct linebuffer *linebuffer, FILE *stream)
50 {
51   int c;
52   char *buffer = linebuffer->buffer;
53   char *p = linebuffer->buffer;
54   char *end = buffer + linebuffer->size; /* Sentinel. */
55
56   if (feof (stream) || ferror (stream))
57     return 0;
58
59   do
60     {
61       c = getc (stream);
62       if (c == EOF)
63         {
64           if (p == buffer)
65             return 0;
66           if (p[-1] == '\n')
67             break;
68           c = '\n';
69         }
70       if (p == end)
71         {
72           linebuffer->size *= 2;
73           buffer = (char *) xrealloc (buffer, linebuffer->size);
74           p = p - linebuffer->buffer + buffer;
75           linebuffer->buffer = buffer;
76           end = buffer + linebuffer->size;
77         }
78       *p++ = c;
79     }
80   while (c != '\n');
81
82   linebuffer->length = p - buffer;
83   return linebuffer;
84 }
85
86 /* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
87
88 void
89 freebuffer (struct linebuffer *linebuffer)
90 {
91   free (linebuffer->buffer);
92   free (linebuffer);
93 }