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

# NAME

getdelim, getline — read a delimited record from a stream

# LIBRARY

Standard C Library (libc, -lc)

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

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

    if (ferror(fp))
    	perror("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”).

June 30, 2010 | NetBSD 7.2