Go to main content

man pages section 3: Basic Library Functions

Exit Print View

Updated: Wednesday, July 27, 2022
 
 

getline(3C)

Name

getline, getdelim - delimited string input

Synopsis

#include <stdio.h>

ssize_t getline(char **restrict lineptr, size_t *restrict n,
FILE *restrict stream);
ssize_t getdelim(char **restrict lineptr, size_t *restrict n,
int delimiter, FILE *restrict stream);

Description

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

If *lineptr is a null pointer, getline() allocates a buffer for storing the line. Alternatively, before the call to getline(), *lineptr can contain a pointer to a buffer allocated by malloc(3C) whose size is *n bytes. If the buffer is not large enough to store the line, getline() resizes the buffer with realloc(3C). In either case, a successful call to getline() updates *lineptr and *n to reflect the buffer address and size, respectively. The buffer should be freed with a call to free(3C).

The getdelim() function is identical to getline(), except a line delimiter other than NEWLINE can be specified as the delimiter argument. As with getline(), a delimiter character is not added if one was not present in stream before end-of-file was reached.

Return Values

Upon successful completion, the getline() and getdelim() functions return the number of characters written into the buffer, including the delimiter character but excluding the terminating null character. Upon failure to read a line (including end of file condition), these function return −1 and set errno to indicate the error.

Errors

The getline() and getdelim() functions will fail if:

EINVAL

Either lineptr or n is a null pointer.

ENOMEM

Insufficient memory is available.

The getline() and getdelim() functions may fail if:

EOVERFLOW

More than {SSIZE_MAX} characters were read without encountering the delimiter character.

See fgetc(3C) for other conditions under which these functions will and may fail.

Examples

Example 1 Retrieve a line length.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(1);
    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }
    if (ferror(fp)) {
        /* handle error */
    }
    free(line);
    fclose(fp);
    return 0;
}

Attributes

See attributes(7) for descriptions of the following 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)