1 /* getline.c -- Replacement for GNU C library function getline
3 Copyright (C) 1993, 1996, 1997, 1998, 2000, 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 Jan Brittenson, bson@gnu.ai.mit.edu. */
28 /* The `getdelim' function is only declared if the following symbol
31 # define _GNU_SOURCE 1
37 #if defined __GNU_LIBRARY__ && HAVE_GETDELIM
40 getline (char **lineptr, size_t *n, FILE *stream)
42 return getdelim (lineptr, n, '\n', stream);
45 #else /* ! have getdelim */
50 char *malloc (), *realloc ();
53 #include "unlocked-io.h"
55 /* Always add at least this many bytes when extending the buffer. */
58 /* Read up to (and including) a delimiter DELIM1 from STREAM into *LINEPTR
59 + OFFSET (and NUL-terminate it). If DELIM2 is non-zero, then read up
60 and including the first occurrence of DELIM1 or DELIM2. *LINEPTR is
61 a pointer returned from malloc (or NULL), pointing to *N characters of
62 space. It is realloc'd as necessary. Return the number of characters
63 read (not including the NUL terminator), or -1 on error or EOF. */
66 getdelim2 (char **lineptr, size_t *n, FILE *stream, int delim1, int delim2,
69 size_t nchars_avail; /* Allocated but unused chars in *LINEPTR. */
70 char *read_pos; /* Where we're reading into *LINEPTR. */
73 if (!lineptr || !n || !stream)
79 *lineptr = malloc (*n);
87 nchars_avail = *n - offset;
88 read_pos = *lineptr + offset;
92 register int c = getc (stream);
94 /* We always want at least one char left in the buffer, since we
95 always (unless we get an error while reading the first char)
96 NUL-terminate the line buffer. */
105 nchars_avail = *n + *lineptr - read_pos;
106 *lineptr = realloc (*lineptr, *n);
109 read_pos = *n - nchars_avail + *lineptr;
112 if (c == EOF || ferror (stream))
114 /* Return partial line, if any. */
115 if (read_pos == *lineptr)
124 if (c == delim1 || (delim2 && c == delim2))
125 /* Return the line. */
129 /* Done - NUL terminate and return the number of chars read. */
132 ret = read_pos - (*lineptr + offset);
138 getline (char **lineptr, size_t *n, FILE *stream)
140 return getdelim2 (lineptr, n, stream, '\n', 0, 0);
144 getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream)
146 return getdelim2 (lineptr, n, stream, delimiter, 0, 0);