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>
30 char *malloc (), *realloc ();
33 /* Always add at least this many bytes when extending the buffer. */
36 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
37 + OFFSET (and null-terminate it). If LIMIT is non-negative, then
38 read no more than LIMIT chars.
40 *LINEPTR is a pointer returned from malloc (or NULL), pointing to
41 *N characters of space. It is realloc'd as necessary.
43 Return the number of characters read (not including the null
44 terminator), or -1 on error or EOF. On a -1 return, the caller
45 should check feof(), if not then errno has been set to indicate the
49 getstr (lineptr
, n
, stream
, terminator
, offset
, limit
)
57 int nchars_avail
; /* Allocated but unused chars in *LINEPTR. */
58 char *read_pos
; /* Where we're reading into *LINEPTR. */
61 if (!lineptr
|| !n
|| !stream
)
70 *lineptr
= malloc (*n
);
79 nchars_avail
= *n
- offset
;
80 read_pos
= *lineptr
+ offset
;
93 /* If limit is negative, then we shouldn't pay attention to
94 it, so decrement only if positive. */
101 /* We always want at least one char left in the buffer, since we
102 always (unless we get an error while reading the first char)
103 NUL-terminate the line buffer. */
105 assert((*lineptr
+ *n
) == (read_pos
+ nchars_avail
));
106 if (nchars_avail
< 2)
113 nchars_avail
= *n
+ *lineptr
- read_pos
;
114 *lineptr
= realloc (*lineptr
, *n
);
120 read_pos
= *n
- nchars_avail
+ *lineptr
;
121 assert((*lineptr
+ *n
) == (read_pos
+ nchars_avail
));
126 /* Might like to return partial line, but there is no
127 place for us to store errno. And we don't want to just
135 /* Return partial line, if any. */
136 if (read_pos
== *lineptr
)
146 /* Return the line. */
150 /* Done - NUL terminate and return the number of chars read. */
153 ret
= read_pos
- (*lineptr
+ offset
);
158 getline (lineptr
, n
, stream
)
163 return getstr (lineptr
, n
, stream
, '\n', 0, GETLINE_NO_LIMIT
);
167 getline_safe (lineptr
, n
, stream
, limit
)
173 return getstr (lineptr
, n
, stream
, '\n', 0, limit
);