1 /* linebuffer.c -- read arbitrarily long lines
3 Copyright (C) 1986, 1991, 1998, 1999, 2001, 2003 Free Software
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20 /* Written by Richard Stallman. */
27 #include <sys/types.h>
28 #include "linebuffer.h"
29 #include "unlocked-io.h"
34 /* Initialize linebuffer LINEBUFFER for use. */
37 initbuffer (struct linebuffer *linebuffer)
39 linebuffer->length = 0;
40 linebuffer->size = 200;
41 linebuffer->buffer = xmalloc (linebuffer->size);
44 /* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
45 Keep the newline; append a newline if it's the last line of a file
46 that ends in a non-newline character. Do not null terminate.
47 Therefore the stream can contain NUL bytes, and the length
48 (including the newline) is returned in linebuffer->length.
49 Return NULL upon error, or when STREAM is empty.
50 Otherwise, return LINEBUFFER. */
52 readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
55 char *buffer = linebuffer->buffer;
56 char *p = linebuffer->buffer;
57 char *end = buffer + linebuffer->size; /* Sentinel. */
59 if (feof (stream) || ferror (stream))
75 linebuffer->size *= 2;
76 buffer = xrealloc (buffer, linebuffer->size);
77 p = p - linebuffer->buffer + buffer;
78 linebuffer->buffer = buffer;
79 end = buffer + linebuffer->size;
85 linebuffer->length = p - buffer;
89 /* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
92 freebuffer (struct linebuffer *linebuffer)
94 free (linebuffer->buffer);