GETDELIM(3) | Library Functions Manual | GETDELIM(3)

# NAME

`getdelim`, `getline` — read a delimited record from a stream

# SYNOPSIS

`#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);

# DESCRIPTION

The `getdelim`() function reads from the stream until it encounters a character matching delimiter, storing the input in *lineptr. The buffer is `NUL`-terminated and includes the delimiter. 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`() will realloc(3) *lineptr as necessary, updating *n to reflect the new size. It is the responsibility of the caller to free(3) *lineptr when it is no longer needed. Even when it fails, `getdelim`() may update *lineptr.

The `getline`() function is equivalent to `getdelim`() with delimiter set to the newline character.

# RETURN VALUES

The `getdelim`() and `getline`() functions return the number of characters read, including the delimiter. 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.

# EXAMPLES

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);

    free(line);
    if (ferror(fp))
    	err(1, "getline");

# ERRORS

[`EINVAL`]
  lineptr or n is a `NULL` pointer.
[`EOVERFLOW`]
  More than SSIZE_MAX characters were read without encountering the delimiter.

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).

# SEE ALSO

ferror(3), fgets(3), fopen(3)

# STANDARDS

The `getdelim`() and `getline`() functions conform to IEEE Std 1003.1-2008 (“POSIX.1”).

# HISTORY

These functions were ported from NetBSD to OpenBSD 5.2.

December 20, 2022 | Debian