1 /* linebuffer.c -- read arbitrarily long lines
3 Copyright (C) 1986, 1991, 1998-1999, 2001, 2003-2004, 2006-2007, 2009-2011
4 Free 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 3 of the License, or
9 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
19 /* Written by Richard Stallman. */
26 #include <sys/types.h>
27 #include "linebuffer.h"
31 # include "unlocked-io.h"
34 /* Initialize linebuffer LINEBUFFER for use. */
37 initbuffer (struct linebuffer *linebuffer)
39 memset (linebuffer, 0, sizeof *linebuffer);
43 readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
45 return readlinebuffer_delim (linebuffer, stream, '\n');
48 /* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
49 Consider lines to be terminated by DELIMITER.
50 Keep the delimiter; append DELIMITER if it's the last line of a file
51 that ends in a character other than DELIMITER. Do not NUL-terminate.
52 Therefore the stream can contain NUL bytes, and the length
53 (including the delimiter) is returned in linebuffer->length.
54 Return NULL when stream is empty. Return NULL and set errno upon
55 error; callers can distinguish this case from the empty case by
56 invoking ferror (stream).
57 Otherwise, return LINEBUFFER. */
59 readlinebuffer_delim (struct linebuffer *linebuffer, FILE *stream,
63 char *buffer = linebuffer->buffer;
64 char *p = linebuffer->buffer;
65 char *end = buffer + linebuffer->size; /* Sentinel. */
75 if (p == buffer || ferror (stream))
77 if (p[-1] == delimiter)
83 size_t oldsize = linebuffer->size;
84 buffer = x2realloc (buffer, &linebuffer->size);
86 linebuffer->buffer = buffer;
87 end = buffer + linebuffer->size;
91 while (c != delimiter);
93 linebuffer->length = p - buffer;
97 /* Free the buffer that was allocated for linebuffer LINEBUFFER. */
100 freebuffer (struct linebuffer *linebuffer)
102 free (linebuffer->buffer);