| GETDELIM(3) | Library Functions Manual | GETDELIM(3) |
getdelim, getline
— read a delimited record from a stream
Standard C Library (libc, -lc)
#include
<stdio.h>
ssize_t
getdelim(char
** restrict lineptr,
size_t * restrict n,
int delimiter,
FILE * restrict
stream);
ssize_t
getline(char
** restrict lineptr,
size_t * restrict n,
FILE * restrict
stream);
The
getdelim()
function reads from the stream until it encounters a
character matching delimiter or
EOF, storing the input in
*lineptr. The buffer is
NUL-terminated and includes
the delimiter, if one was found. The delimiter
character must be representable as an unsigned char.
If *n is non-zero, then
*lineptr must be pre-allocated to at least
*n bytes. The buffer should be allocated dynamically;
it must be possible to free(3)
*lineptr.
getdelim()
ensures that *lineptr is large enough to hold the
input, updating *n to reflect the new size.
The
getline()
function is equivalent to getdelim() with
delimiter set to the newline character.
The getdelim() and
getline() functions return the number of characters
read, including the delimiter if one was found. If no characters were read
and the stream is at end-of-file, the functions return -1. If an error
occurs, the functions return -1 and the global variable
errno is set to indicate the error.
The functions do not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
The following code fragment reads lines from a file and writes them to standard output.
char *line = NULL;
size_t linesize = 0;
ssize_t linelen;
while ((linelen = getline(&line, &linesize, fp)) != -1)
fwrite(line, linelen, 1, stdout);
if (ferror(fp))
perror("getline");
EINVAL]NULL pointer.EOVERFLOW]The getdelim() and
getline() functions may also fail and set
errno for any of the errors specified in the routines
fflush(3),
malloc(3),
read(2),
stat(2), or
realloc(3).
The getdelim() and
getline() functions conform to IEEE
Std 1003.1-2008 (“POSIX.1”).
The
getdelim()
and getline() functions can return results that
include NUL characters, which can cause the apparent
length reported by strlen(3)
to be less than the true length reported by the return values of the
functions.
| September 15, 2014 | NetBSD 11.0 |