*** empty log message ***
[coreutils.git] / lib / linebuffer.c
blob8374a8a880bd6ffa617347ec26fee181d4150d28
1 /* linebuffer.c -- read arbitrarily long lines
2 Copyright (C) 1986, 1991, 1998, 1999, 2001 Free Software Foundation, Inc.
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.
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.
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. */
18 /* Written by Richard Stallman. */
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include "linebuffer.h"
27 #include "unlocked-io.h"
28 #include "xalloc.h"
30 void free ();
32 /* Initialize linebuffer LINEBUFFER for use. */
34 void
35 initbuffer (struct linebuffer *linebuffer)
37 linebuffer->length = 0;
38 linebuffer->size = 200;
39 linebuffer->buffer = xmalloc (linebuffer->size);
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 Therefore the stream can contain NUL bytes, and the length
46 (including the newline) is returned in linebuffer->length.
47 Return NULL upon error, or when STREAM is empty.
48 Otherwise, return LINEBUFFER. */
49 struct linebuffer *
50 readline (struct linebuffer *linebuffer, FILE *stream)
52 int c;
53 char *buffer = linebuffer->buffer;
54 char *p = linebuffer->buffer;
55 char *end = buffer + linebuffer->size; /* Sentinel. */
57 if (feof (stream) || ferror (stream))
58 return NULL;
62 c = getc (stream);
63 if (c == EOF)
65 if (p == buffer)
66 return NULL;
67 if (p[-1] == '\n')
68 break;
69 c = '\n';
71 if (p == end)
73 linebuffer->size *= 2;
74 buffer = xrealloc (buffer, linebuffer->size);
75 p = p - linebuffer->buffer + buffer;
76 linebuffer->buffer = buffer;
77 end = buffer + linebuffer->size;
79 *p++ = c;
81 while (c != '\n');
83 linebuffer->length = p - buffer;
84 return linebuffer;
87 /* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
89 void
90 freebuffer (struct linebuffer *linebuffer)
92 free (linebuffer->buffer);
93 free (linebuffer);