1 /* getline.c -- Replacement for GNU C library function getline
3 Copyright (C) 1993 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details. */
15 /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */
21 #include <sys/types.h>
29 char *malloc (), *realloc ();
32 /* Always add at least this many bytes when extending the buffer. */
35 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
36 + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
37 malloc (or NULL), pointing to *N characters of space. It is realloc'd
38 as necessary. Return the number of characters read (not including the
39 null terminator), or -1 on error or EOF. On a -1 return, the caller
40 should check feof(), if not then errno has been set to indicate
44 getstr (lineptr, n, stream, terminator, offset)
51 int nchars_avail; /* Allocated but unused chars in *LINEPTR. */
52 char *read_pos; /* Where we're reading into *LINEPTR. */
55 if (!lineptr || !n || !stream)
64 *lineptr = malloc (*n);
72 nchars_avail = *n - offset;
73 read_pos = *lineptr + offset;
78 register int c = getc (stream);
82 /* We always want at least one char left in the buffer, since we
83 always (unless we get an error while reading the first char)
84 NUL-terminate the line buffer. */
86 assert((*lineptr + *n) == (read_pos + nchars_avail));
94 nchars_avail = *n + *lineptr - read_pos;
95 *lineptr = realloc (*lineptr, *n);
101 read_pos = *n - nchars_avail + *lineptr;
102 assert((*lineptr + *n) == (read_pos + nchars_avail));
107 /* Might like to return partial line, but there is no
108 place for us to store errno. And we don't want to just
116 /* Return partial line, if any. */
117 if (read_pos == *lineptr)
127 /* Return the line. */
131 /* Done - NUL terminate and return the number of chars read. */
134 ret = read_pos - (*lineptr + offset);
139 getline (lineptr, n, stream)
144 return getstr (lineptr, n, stream, '\n', 0);