]>
diplodocus.org Git - nmh/blob - sbr/getline.c
2 * getline.c -- replacement getline() implementation
4 * This code is Copyright (c) 2016, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
15 #else /* ! HAVE_STDBOOL_H */
19 #endif /* ! HAVE_STDBOOL_H */
21 /* Largest possible size of buffer that allows SSIZE_MAX to be returned
22 * to indicate SSIZE_MAX - 1 characters read before the '\n'. The
23 * additional 1 is for the terminating NUL. */
24 #define MAX_AVAIL ((size_t)SSIZE_MAX + 1)
26 /* Ideal increase in size of line buffer. */
29 ssize_t
getline(char **lineptr
, size_t *n
, FILE *stream
)
44 avail
= *n
<= MAX_AVAIL
? *n
: MAX_AVAIL
;
46 avail
= *n
= 0; /* POSIX allows *lineptr = NULL, *n = 42. */
52 if (ferror(stream
) || /* errno set by stdlib. */
53 !used
) /* EOF with nothing read. */
55 /* Line will be returned without a \n terminator. */
65 if (avail
== MAX_AVAIL
) {
69 want
= avail
+ GROWTH
;
72 new = realloc(l
, want
);
74 return -1; /* errno set by stdlib. */
81 return used
- 1; /* Don't include NUL. */
84 goto append_nul
; /* Final half loop. */