1 /* getline.c -- Replacement for GNU C library function getline
3 Copyright (C) 1993, 1996, 1997 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 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */
25 /* The `getdelim' function is only declared if the following symbol
28 # define _GNU_SOURCE 1
32 #include <sys/types.h>
34 #if defined __GNU_LIBRARY__ && HAVE_GETDELIM
37 getline (lineptr
, n
, stream
)
42 return getdelim (lineptr
, n
, '\n', stream
);
46 #else /* ! have getdelim */
54 char *malloc (), *realloc ();
57 /* Always add at least this many bytes when extending the buffer. */
60 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
61 + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
62 malloc (or NULL), pointing to *N characters of space. It is realloc'd
63 as necessary. Return the number of characters read (not including the
64 null terminator), or -1 on error or EOF. */
67 getstr (lineptr
, n
, stream
, terminator
, offset
)
74 int nchars_avail
; /* Allocated but unused chars in *LINEPTR. */
75 char *read_pos
; /* Where we're reading into *LINEPTR. */
78 if (!lineptr
|| !n
|| !stream
)
84 *lineptr
= malloc (*n
);
89 nchars_avail
= *n
- offset
;
90 read_pos
= *lineptr
+ offset
;
94 register int c
= getc (stream
);
96 /* We always want at least one char left in the buffer, since we
97 always (unless we get an error while reading the first char)
98 NUL-terminate the line buffer. */
100 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
101 if (nchars_avail
< 2)
108 nchars_avail
= *n
+ *lineptr
- read_pos
;
109 *lineptr
= realloc (*lineptr
, *n
);
112 read_pos
= *n
- nchars_avail
+ *lineptr
;
113 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
116 if (c
== EOF
|| ferror (stream
))
118 /* Return partial line, if any. */
119 if (read_pos
== *lineptr
)
129 /* Return the line. */
133 /* Done - NUL terminate and return the number of chars read. */
136 ret
= read_pos
- (*lineptr
+ offset
);
141 getline (lineptr
, n
, stream
)
146 return getstr (lineptr
, n
, stream
, '\n', 0);
150 getdelim (lineptr
, n
, delimiter
, stream
)
156 return getstr (lineptr
, n
, stream
, delimiter
, 0);