get_next_line

A C function that reads a file descriptor line by line, demonstrating mastery of static variables and buffer manipulation.

2021-05-01

low-levelOpen GitHub
get_next_line

get_next_line

A C function that reads one line at a time from a file descriptor, picking up exactly where it left off on each call. Works with any fd including stdin and sockets. A static buffer keeps leftover bytes between calls so nothing gets lost when lines span buffer boundaries.

Signature

char *get_next_line(int fd);

Returns the next line as a heap-allocated string (including the \n), or NULL at EOF or on error. The caller frees it.

How the state works

Call 1: read() fills buffer, find '\n', return line 1,
        keep the rest in the static buffer

Call 2: prepend static buffer, search for '\n' again
        (another read() if needed)

Call N: hit EOF, return whatever's left, reset

BUFFER_SIZE is set at compile time and controls how many bytes each read() call pulls in.

Bonus: multiple file descriptors

The bonus version handles multiple fds at the same time with independent read state for each one:

char *line_a  = get_next_line(fd_a);
char *line_b  = get_next_line(fd_b);  // doesn't interfere with fd_a
char *line_a2 = get_next_line(fd_a);  // picks up where fd_a left off

Compile

cc -Wall -Wextra -Werror -D BUFFER_SIZE=42 \
   get_next_line.c get_next_line_utils.c -o gnl

Edge cases covered

  • Empty files
  • Files with no trailing newline
  • Lines longer than BUFFER_SIZE
  • BUFFER_SIZE=1 (byte-by-byte reads)
  • Multiple simultaneous fds (bonus)
  • read() errors mid-stream

SCREENSHOTS // 01 FRAMES

Screenshot 1
01 / 01