]>
diplodocus.org Git - nmh/blob - sbr/getline.c
1 /* getline.c -- replacement getline() implementation
3 * This code is Copyright (c) 2016, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
15 /* Largest possible size of buffer that allows SSIZE_MAX to be returned
16 * to indicate SSIZE_MAX - 1 characters read before the '\n'. The
17 * additional 1 is for the terminating NUL. */
18 #define MAX_AVAIL ((size_t)SSIZE_MAX + 1)
20 /* Ideal increase in size of line buffer. */
23 ssize_t
getline(char **lineptr
, size_t *n
, FILE *stream
)
38 avail
= *n
<= MAX_AVAIL
? *n
: MAX_AVAIL
;
40 avail
= *n
= 0; /* POSIX allows *lineptr = NULL, *n = 42. */
46 if (ferror(stream
) || /* errno set by stdlib. */
47 !used
) /* EOF with nothing read. */
49 /* Line will be returned without a \n terminator. */
59 if (avail
== MAX_AVAIL
) {
63 want
= avail
+ GROWTH
;
66 new = realloc(l
, want
);
68 return -1; /* errno set by stdlib. */
75 return used
- 1; /* Don't include NUL. */
78 goto append_nul
; /* Final half loop. */