← Back to projects

get_next_line

Reading a file descriptor line by line in C, with a static buffer kept between calls and no memory leak.

Period
21/12/2021
Category
42
Area
Systems
Grade
125
Stack
  • C
Links

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.