]>
git.ipfire.org Git - people/ms/u-boot.git/blob - tools/getline.c
1 /* getline.c -- Replacement for GNU C library function getline
3 * Copyright (C) 1993, 1996, 2001, 2002 Free Software Foundation, Inc.
5 * SPDX-License-Identifier: GPL-2.0+
8 /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */
13 /* Always add at least this many bytes when extending the buffer. */
16 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
17 + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
18 malloc (or NULL), pointing to *N characters of space. It is realloc'd
19 as necessary. Return the number of characters read (not including the
20 null terminator), or -1 on error or EOF.
21 NOTE: There is another getstr() function declared in <curses.h>. */
22 static int getstr(char **lineptr
, size_t *n
, FILE *stream
,
23 char terminator
, size_t offset
)
25 int nchars_avail
; /* Allocated but unused chars in *LINEPTR. */
26 char *read_pos
; /* Where we're reading into *LINEPTR. */
29 if (!lineptr
|| !n
|| !stream
)
34 *lineptr
= malloc(*n
);
39 nchars_avail
= *n
- offset
;
40 read_pos
= *lineptr
+ offset
;
43 register int c
= getc(stream
);
45 /* We always want at least one char left in the buffer, since we
46 always (unless we get an error while reading the first char)
47 NUL-terminate the line buffer. */
49 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
50 if (nchars_avail
< 2) {
56 nchars_avail
= *n
+ *lineptr
- read_pos
;
57 *lineptr
= realloc(*lineptr
, *n
);
60 read_pos
= *n
- nchars_avail
+ *lineptr
;
61 assert(*n
- nchars_avail
== read_pos
- *lineptr
);
64 if (c
== EOF
|| ferror (stream
)) {
65 /* Return partial line, if any. */
66 if (read_pos
== *lineptr
)
76 /* Return the line. */
80 /* Done - NUL terminate and return the number of chars read. */
83 ret
= read_pos
- (*lineptr
+ offset
);
87 int getline (char **lineptr
, size_t *n
, FILE *stream
)
89 return getstr(lineptr
, n
, stream
, '\n', 0);