Process Lines Efficiently with getline
Read lines of any length in C with getline, reuse one growing buffer, strip the newline, spot read errors and handle files without a final newline.

Reading a line of text in C looks easy until the line is longer than your buffer. gets was removed from the language because it could not be used safely, and fgets truncates a long line silently and leaves the rest for the next call. POSIX.1-2008 added getline, which reads a whole line of any length into a buffer that it allocates and grows for you. This post shows how to use it on Linux with glibc 2.40: the buffer-reuse pattern that keeps it efficient, how to find the line length and the newline, how to tell end of file from an error, and where it can still hurt you. It is the line-oriented counterpart to the block copy in the guide to command-line tools in C.
The signature and what it promises
getline is declared in <stdio.h>, and on glibc it needs _POSIX_C_SOURCE 200809L or _GNU_SOURCE before the include, since it is not in ISO C. The prototype is:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);You give it the address of a char * and the address of a size_t that holds the current buffer size. If the pointer is NULL and the size is 0, it allocates a buffer. If the buffer is too small for the line, it calls realloc to enlarge it and updates both values. It reads up to and including the newline, stores the text with a terminating NUL byte, and returns the number of bytes read, not counting the NUL. At end of file, or on an error, it returns -1. See getline(3).
Three consequences follow directly.
The returned length includes the newline, if there was one.
The buffer belongs to you. After the last call, you
freeit once.The contents are valid only until the next call, because the next line overwrites them. To keep a line, copy it with
strdupormemcpy.
The reuse pattern
The efficient way to use getline is to declare the pointer and size once, outside the loop, and pass them to every call. The buffer grows to fit the longest line seen so far and is then reused for every later one, so a file with a million short lines does about one allocation, not a million.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *in = stdin;
if (argc > 1) {
in = fopen(argv[1], "r");
if (in == NULL) {
perror(argv[1]);
return 1;
}
}
char *line = NULL;
size_t cap = 0;
ssize_t len;
unsigned long lines = 0, longest = 0, total = 0;
while ((len = getline(&line, &cap, in)) != -1) {
if (len > 0 && line[len - 1] == '\n')
line[--len] = '\0';
lines++;
total += (unsigned long)len;
if ((unsigned long)len > longest)
longest = (unsigned long)len;
}
int failed = ferror(in);
free(line);
if (in != stdin)
fclose(in);
if (failed) {
fprintf(stderr, "%s: read error\n", argv[0]);
return 1;
}
printf("lines=%lu longest=%lu total=%lu\n", lines, longest, total);
return 0;
}Feed it three lines, alpha, be and gamma-ray, each ended with a newline, and it prints:
lines=3 longest=9 total=16The lengths are 5, 2 and 9, which sum to 16, and the newline characters were removed before counting. The program never decides how big a line may be. A line of ten megabytes works, because getline keeps doubling the buffer until it fits, and cap records the final size.
Stripping the newline correctly
The idiom line[len - 1] == '\n' followed by line[--len] = '\0' is the common one, and it has a guard that matters. The last line of a file may have no newline, so you cannot assume the last byte is one. Without the check, a file ending with x and no newline would lose the x. The len > 0 test is there for a different reason: a line that is empty cannot arise from getline on a text file, because every returned line contains at least one byte, but defensive code keeps the check cheap and clear.
A tidier alternative uses strcspn, which returns the length of the initial part of a string that contains none of the listed characters:
line[strcspn(line, "\n")] = '\0';It strips the first newline wherever it is and does nothing if there is none. It costs a scan of the line, and it is wrong when the line contains an embedded NUL before the newline, because strcspn stops at the NUL. If you already have len from getline, the direct test is both cheaper and exact.
Windows text files end lines with a carriage return and a newline. After stripping the newline, a stray \r stays at the end of the line on Linux, and it shows up as an invisible character that breaks string comparison. A tool that reads files from other systems strips a trailing '\r' as well.
Telling end of file from an error
getline returns -1 in both cases. After the loop, feof(in) is true for a clean end, and ferror(in) is true for a read error. Check ferror and report the error, or a disk fault in the middle of a file looks like a short file. The example does that and sets the exit status. Where errno is meaningful, getline also sets it on failure: EINVAL for a bad argument, ENOMEM when it cannot grow the buffer, and the usual I/O codes such as EIO otherwise.
A second case worth knowing is a read interrupted by a signal. getline goes through stdio, which restarts the underlying read when a handler was installed with SA_RESTART. Without SA_RESTART, an interrupted read can fail with EINTR, the stream's error flag is set and getline returns -1. A program that installs signal handlers must either use SA_RESTART or clear the error with clearerr and retry.
Embedded NUL bytes
getline is a binary-safe read: it keeps every byte, including NUL, up to the newline. The len it returns is the true length, so a line that contains a, NUL, b has length 3. The C string functions, though, stop at the first NUL, so strlen(line) returns 1 for that line. Code that handles untrusted text must decide what a NUL in the middle of a line means. The safe choices are to reject the line, or to carry len along and use memchr, memcmp and fwrite instead of the string functions.
This matters in tools that print what they read. puts(line) and printf("%s", line) stop at the NUL and drop the rest silently. fwrite(line, 1, len, stdout) prints the whole line, including the newline you did not strip.
Other delimiters with getdelim
getline is a special case of getdelim, which takes the delimiter character as a parameter:
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);Records separated by NUL bytes, produced by find -print0, are read with getdelim(&rec, &cap, '\0', stdin). Using NUL as the separator is the safe way to pass file names, which can legally contain newlines. Tools that accept -0 or --null options use exactly this call. Everything said above carries over: the returned length includes the delimiter, and the buffer is reused.
Limits you set yourself
getline places no ceiling on the line length. That is its strength and its risk. A file with no newline in a gigabyte of data makes it try to allocate a gigabyte, and a hostile input can exhaust memory. A tool that reads untrusted input should enforce a maximum, and since getline offers no parameter for it, the options are:
Check
lenafter each call and abort or truncate when it exceeds the limit. This protects the logic after the read, but the buffer has already grown.Use
fgetswith a fixed buffer and handle the "line did not end in a newline" case by discarding the rest of the line. It bounds memory exactly, and the loop that discards is a few lines.Cap the process with
setrlimit(RLIMIT_AS, ...), so that growth fails withENOMEMinstead of consuming the machine.
For trusted input such as a configuration file or the output of another program you wrote, the unlimited behaviour is fine.
Performance
The mechanism explains why getline is a good default. It reads through stdio's buffer, so most calls are served from memory and the system call happens once per block. It locks the stream on each call, which costs a little in a single-threaded program, and the getc_unlocked family or getline-free code avoids that at the price of portability and clarity. For a tool whose job is counting bytes rather than lines, reading blocks with read is faster still, because nothing scans for the newline. No benchmark is needed to choose: use getline when you need lines, and a block read when you need bytes.
Common mistakes
Declaring the buffer inside the loop. A new
char *line = NULLeach iteration leaks the previous allocation and defeats the reuse.Passing a stack array. The first argument must be a pointer that
malloccan resize, orNULL. A buffer from the stack makesrealloccrash.Freeing inside the loop. Free once, after the last call.
**Keeping a pointer to
lineacross calls.** The next call overwrites it, or moves it.**Ignoring
ferror.** A failing disk then looks like a short, valid file.


