(readline): Do not leave room for an extra
[gnulib.git] / lib / linebuffer.c
1 /* linebuffer.c -- read arbitrarily long lines
2    Copyright (C) 1986, 1991, 1998, 1999 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
28 char *xmalloc ();
29 char *xrealloc ();
30 void free ();
31
32 /* Initialize linebuffer LINEBUFFER for use. */
33
34 void
35 initbuffer (struct linebuffer *linebuffer)
36 {
37   linebuffer->length = 0;
38   linebuffer->size = 200;
39   linebuffer->buffer = (char *) xmalloc (linebuffer->size);
40 }
41
42 /* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
43    Keep the newline; append a newline if it's the last line of a file
44    that ends in a non-newline character.  Do not null terminate.
45    Return LINEBUFFER, except at end of file return 0.  */
46
47 struct linebuffer *
48 readline (struct linebuffer *linebuffer, FILE *stream)
49 {
50   int c;
51   char *buffer = linebuffer->buffer;
52   char *p = linebuffer->buffer;
53   char *end = buffer + linebuffer->size; /* Sentinel. */
54
55   if (feof (stream) || ferror (stream))
56     return 0;
57
58   do
59     {
60       c = getc (stream);
61       if (c == EOF)
62         {
63           if (p == buffer)
64             return 0;
65           if (p[-1] == '\n')
66             break;
67           c = '\n';
68         }
69       if (p == end)
70         {
71           linebuffer->size *= 2;
72           buffer = (char *) xrealloc (buffer, linebuffer->size);
73           p = p - linebuffer->buffer + buffer;
74           linebuffer->buffer = buffer;
75           end = buffer + linebuffer->size;
76         }
77       *p++ = c;
78     }
79   while (c != '\n');
80
81   linebuffer->length = p - buffer;
82   return linebuffer;
83 }
84
85 /* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
86
87 void
88 freebuffer (struct linebuffer *linebuffer)
89 {
90   free (linebuffer->buffer);
91   free (linebuffer);
92 }