(readline): Return zero upon error as well as upon
[gnulib.git] / lib / linebuffer.c
1 /* linebuffer.c -- read arbitrarily long lines
2    Copyright (C) 1986, 1991, 1998 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
16    Foundation, 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 "linebuffer.h"
26
27 char *xmalloc ();
28 char *xrealloc ();
29 void free ();
30
31 /* Initialize linebuffer LINEBUFFER for use. */
32
33 void
34 initbuffer (linebuffer)
35      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    Remove any newline.  Does not null terminate.
44    Return zero upon error or upon end of file.
45    Otherwise, return LINEBUFFER.  */
46
47 struct linebuffer *
48 readline (linebuffer, stream)
49      struct linebuffer *linebuffer;
50      FILE *stream;
51 {
52   int c;
53   char *buffer = linebuffer->buffer;
54   char *p = linebuffer->buffer;
55   char *end = buffer + linebuffer->size; /* Sentinel. */
56
57   if (feof (stream) || ferror (stream))
58     {
59       linebuffer->length = 0;
60       return 0;
61     }
62
63   while (1)
64     {
65       c = getc (stream);
66       if (p == end)
67         {
68           linebuffer->size *= 2;
69           buffer = (char *) xrealloc (buffer, linebuffer->size);
70           p += buffer - linebuffer->buffer;
71           linebuffer->buffer = buffer;
72           end = buffer + linebuffer->size;
73         }
74       if (c == EOF || c == '\n')
75         break;
76       *p++ = c;
77     }
78
79   if (feof (stream) && p == buffer)
80     {
81       linebuffer->length = 0;
82       return 0;
83     }
84   linebuffer->length = p - linebuffer->buffer;
85   return linebuffer;
86 }
87
88 /* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
89
90 void
91 freebuffer (linebuffer)
92      struct linebuffer *linebuffer;
93 {
94   free (linebuffer->buffer);
95   free (linebuffer);
96 }