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., 675 Mass Ave, Cambridge, MA 02139, USA. */
19 /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */
25 #include <sys/types.h>
33 char *malloc (), *realloc ();
36 /* Always add at least this many bytes when extending the buffer. */
39 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
40 + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
41 malloc (or NULL), pointing to *N characters of space. It is realloc'd
42 as necessary. Return the number of characters read (not including the
43 null terminator), or -1 on error or EOF. */
46 getstr (lineptr
, n
, stream
, terminator
, offset
)
53 int nchars_avail
; /* Allocated but unused chars in *LINEPTR. */
54 char *read_pos
; /* Where we're reading into *LINEPTR. */
57 if (!lineptr
|| !n
|| !stream
)
63 *lineptr
= malloc (*n
);
68 nchars_avail
= *n
- offset
;
69 read_pos
= *lineptr
+ offset
;
73 register int c
= getc (stream
);
75 /* We always want at least one char left in the buffer, since we
76 always (unless we get an error while reading the first char)
77 NUL-terminate the line buffer. */
79 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
87 nchars_avail
= *n
+ *lineptr
- read_pos
;
88 *lineptr
= realloc (*lineptr
, *n
);
91 read_pos
= *n
- nchars_avail
+ *lineptr
;
92 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
95 if (c
== EOF
|| ferror (stream
))
97 /* Return partial line, if any. */
98 if (read_pos
== *lineptr
)
108 /* Return the line. */
112 /* Done - NUL terminate and return the number of chars read. */
115 ret
= read_pos
- (*lineptr
+ offset
);
120 getline (lineptr
, n
, stream
)
125 return getstr (lineptr
, n
, stream
, '\n', 0);