Start of change

getline() — Read an entire line from a stream

Standards

Standards / Extensions C or C++ Dependencies
POSIX.1-2008
Single UNIX Specification, Version 4
both  

Format

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
ssize_t getline(char **__restrict__ lineptr, size_t *__restrict__ n, FILE *__restrict__ stream);

General description

The getline() function reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one is found.

If *lineptr is set to NULL and *n is set 0 before the call, getline() allocates a buffer for storing the line. This buffer must be freed by the user program even when getline() fails.

Alternatively, before calling getline(), *lineptr can contain a pointer to a buffer that is allocated by malloc(), which is *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(), updating *lineptr and *n as necessary.

In either case, on a successful call, *lineptr and *n are updated to reflect the buffer address and allocated size respectively.

Returned value

If successful, getline() returns the number of characters that are read, including the newline character, but not including the terminating null byte (‘\0’). This value can be used to handle embedded null bytes in the line read.

If unsuccessful, getline() returns -1 and sets errno to one of the following values:
Error Code
Description
EINVAL
Invalid arguments. *lineptr or *n is NULL, or stream is not valid.
ENOMEM
Allocation or reallocation of the line buffer fails.
Start of changeERECIOEnd of change
Start of changeFile opened for record I/O. Cannot get single bytes.End of change
Start of changeEOVERFLOWEnd of change
Start of changeLine length is too large, which exceeds the maximum value that the returning type ssize_t can represent.End of change

Related information

End of change