GETLINE(3C) Standard C Library Functions GETLINE(3C)
NAME
getline, getdelim - read delimited input from streams
SYNOPSIS
#include <stdio.h>
ssize_t getline(
char **restrict ptr,
size_t *restrict cap,
FILE *restrict stream);
ssize_t getdelim(
char **restrict ptr,
size_t *restrict cap,
int delimiter,
FILE *restrict stream);
DESCRIPTION
The
getdelim() function reads bytes from the
stream into the array
pointed to by
ptr, until the
delimiter byte or an end-of-file
condition is encountered. The
getline() function is identical in
behaviour, but uses the newline character as the delimiter. The
delimiter character is included in the string (unless end-of-file was
reached first) and the string is terminated with a null byte.
The caller may pass a pre-allocated
malloc(3C) buffer as
*ptr, along
with the capacity of that buffer as
*cap. It is also valid to pass
NULL for
*ptr and
0 for
*cap, at which point memory will be allocated
automatically. If the buffer provided is not large enough to hold
the string it will be expanded, as if via
realloc(3C). The caller
must
free(3C) the buffer when it is no longer required.
RETURN VALUES
If successful,
getdelim() and
getline() return the number of bytes
written into the buffer, excluding the terminating null byte. If an
error occurs, or if end-of-file is reached prior to reading any
bytes, the value
-1 is returned and
errno is set to indicate the
error.
ERRORS
The
getline() and
getdelim() functions may fail due to the following
errors:
EINVAL Either
ptr or
cap are
NULL, or the
delimiter is not a
valid character.
EOVERFLOW More than
SSIZE_MAX characters were read from the stream
without encountering the
delimiter.
The
getline() and
getdelim() functions may also fail and set
errno for any of the errors specified for the library routines
realloc(3C) or
fgetc(3C).
EXAMPLES
Example 1: Read a line from stdin.
The following example uses
getline to read a line from stdin.
#include <stdio.h>
...
char *ptr = NULL;
size_t cap = 0;
if (getline(&ptr, &cap, stdin) == -1) {
perror("getline");
exit(1);
}
fprintf(stdout, "input line: %s", ptr);
free(ptr);
ATTRIBUTES
+--------------------+-----------------+
| ATTRIBUTE TYPE | ATTRIBUTE VALUE |
+--------------------+-----------------+
|Interface Stability | Committed |
+--------------------+-----------------+
|MT-Level | MT-Safe |
+--------------------+-----------------+
SEE ALSO
fgetc(3C),
fgets(3C),
free(3C),
malloc(3C),
realloc(3C),
attributes(7) April 9, 2016 GETLINE(3C)