1 /* linebuffer.c -- read arbitrarily long lines
3 Copyright (C) 1986, 1991, 1998, 1999, 2001, 2003, 2004, 2006 Free
4 Software Foundation, Inc.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* Written by Richard Stallman. */
27 #include <sys/types.h>
28 #include "linebuffer.h"
32 # include "unlocked-io.h"
35 /* Initialize linebuffer LINEBUFFER for use. */
38 initbuffer (struct linebuffer *linebuffer)
40 memset (linebuffer, 0, sizeof *linebuffer);
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 Therefore the stream can contain NUL bytes, and the length
47 (including the newline) is returned in linebuffer->length.
48 Return NULL when stream is empty. Return NULL and set errno upon
49 error; callers can distinguish this case from the empty case by
50 invoking ferror (stream).
51 Otherwise, return LINEBUFFER. */
53 readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
56 char *buffer = linebuffer->buffer;
57 char *p = linebuffer->buffer;
58 char *end = buffer + linebuffer->size; /* Sentinel. */
68 if (p == buffer || ferror (stream))
76 size_t oldsize = linebuffer->size;
77 buffer = x2realloc (buffer, &linebuffer->size);
79 linebuffer->buffer = buffer;
80 end = buffer + linebuffer->size;
86 linebuffer->length = p - buffer;
90 /* Free the buffer that was allocated for linebuffer LINEBUFFER. */
93 freebuffer (struct linebuffer *linebuffer)
95 free (linebuffer->buffer);