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 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. */
26 #include <sys/types.h>
28 #if defined __GNU_LIBRARY__ && defined HAVE_GETDELIM
31 getline (lineptr
, n
, stream
)
36 return getdelim (lineptr
, n
, '\n', stream
);
40 #else /* ! have getdelim */
48 char *malloc (), *realloc ();
51 /* Always add at least this many bytes when extending the buffer. */
54 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
55 + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
56 malloc (or NULL), pointing to *N characters of space. It is realloc'd
57 as necessary. Return the number of characters read (not including the
58 null terminator), or -1 on error or EOF. */
61 getstr (lineptr
, n
, stream
, terminator
, offset
)
68 int nchars_avail
; /* Allocated but unused chars in *LINEPTR. */
69 char *read_pos
; /* Where we're reading into *LINEPTR. */
72 if (!lineptr
|| !n
|| !stream
)
78 *lineptr
= malloc (*n
);
83 nchars_avail
= *n
- offset
;
84 read_pos
= *lineptr
+ offset
;
88 register int c
= getc (stream
);
90 /* We always want at least one char left in the buffer, since we
91 always (unless we get an error while reading the first char)
92 NUL-terminate the line buffer. */
94 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
102 nchars_avail
= *n
+ *lineptr
- read_pos
;
103 *lineptr
= realloc (*lineptr
, *n
);
106 read_pos
= *n
- nchars_avail
+ *lineptr
;
107 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
110 if (c
== EOF
|| ferror (stream
))
112 /* Return partial line, if any. */
113 if (read_pos
== *lineptr
)
123 /* Return the line. */
127 /* Done - NUL terminate and return the number of chars read. */
130 ret
= read_pos
- (*lineptr
+ offset
);
135 getline (lineptr
, n
, stream
)
140 return getstr (lineptr
, n
, stream
, '\n', 0);
144 getdelim (lineptr
, n
, delimiter
, stream
)
150 return getstr (lineptr
, n
, stream
, delimiter
, 0);