A function that reads a file descriptor line by line. Each call returns the next line (including \n), using a static buffer to keep track of leftover data between calls.
#include "get_next_line.h"
int fd = open("file.txt", O_RDONLY);
char *line;
while ((line = get_next_line(fd)) != NULL)
{
printf("%s", line);
free(line);
}
close(fd);Compile with a custom buffer size:
cc -D BUFFER_SIZE=64 get_next_line.c get_next_line_utils.cA static variable persists between calls. On each call, read() fills a temporary buffer (BUFFER_SIZE bytes) and appends to the static buffer until a \n is found or EOF is reached. When a newline is found, everything up to it is returned and the rest stays in the buffer for next time.
The bonus version handles multiple file descriptors at the same time. Each fd has its own buffer, so you can alternate between files without them interfering.
char *line1 = get_next_line(fd1); // reads from file 1
char *line2 = get_next_line(fd2); // reads from file 2, fd1 buffer untouched
char *line3 = get_next_line(fd1); // continues where fd1 left off├── get_next_line.h - prototype + BUFFER_SIZE default
├── get_next_line.c - main function (single fd)
├── get_next_line_utils.c - string helpers
├── get_next_line_bonus.h - bonus prototype
├── get_next_line_bonus.c - multi-fd version
└── get_next_line_utils_bonus.c - bonus helpers