get_next_line

One line at a time

Reading one line means reading too much, and remembering the rest.

The function returns the next line of a file descriptor, and behaves the same on a file, on standard input or on a redirection. A static variable keeps whatever was read past the line, whatever the buffer size, which is fixed at compile time.

Area
  • 42
  • library
  • buffers
Stack
C
Grade
125%
Date
2021

Reading a file descriptor one line at a time, until EOF.

What it does

get_next_line returns the next line — newline included — from a file descriptor. Called in a loop it walks a whole file, and it behaves the same on a regular file, on standard input or on a redirection. The bonus version keeps several descriptors open at once without ever mixing their contents.

How it works

A static variable holds whatever was read past the end of the current line, so the next call starts where the previous one stopped. The read size is a compile-time constant (-D BUFFER_SIZE=xx), which means the function has to behave identically whether it reads one byte or a megabyte at a time.

What it taught me

Static variables and their lifetime, and how much care partial reads demand: every branch has to free what it allocated, including the ones that only run on an error.