This project has been created as part of the 42 curriculum by belaindr.
get_next_line is a C function that reads a line from a file descriptor, one line at a time. Each call to the function returns the next line from the file descriptor, including the terminating \n character (except at end of file if no trailing newline exists). It returns NULL when there is nothing left to read or if an error occurs.
The project introduces a key concept in C programming: static variables, which allow a function to retain state between successive calls.
| File | Description |
|---|---|
get_next_line.c |
Core function implementation |
get_next_line_utils.c |
Helper functions |
get_next_line.h |
Header file with function prototype |
Bonus files:
get_next_line_bonus.cget_next_line_utils_bonus.cget_next_line_bonus.h
cc -Wall -Wextra -Werror -D BUFFER_SIZE=42 get_next_line.c get_next_line_utils.cThe BUFFER_SIZE macro defines how many bytes are read at a time. You can adjust this value freely. The project must compile with or without the -D BUFFER_SIZE flag.
#include "get_next_line.h"
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd;
char *line;
fd = open("file.txt", O_RDONLY);
while ((line = get_next_line(fd)) != NULL)
{
printf("%s", line);
free(line);
}
close(fd);
return (0);
}The function uses a static buffer (leftover) approach:
- A
static char *variable retains any data read beyond the last newline between calls. - On each call, the function first checks the leftover for a newline. If one is found, it extracts and returns the line without reading more from the file descriptor.
- If no newline is found in the leftover, it reads chunks of
BUFFER_SIZEbytes from the file descriptor, appending each chunk to the leftover, until a newline is found or EOF is reached. - Once a newline (or EOF) is detected, the line up to and including
\nis extracted and returned. The remainder is saved back into the static variable for the next call.
Why this approach?
It minimizes unnecessary reads — the function reads only as much as needed per call. The static variable elegantly solves the problem of keeping unconsumed data between calls without using global variables or requiring the caller to manage state.
Bonus: For multiple file descriptor support, the static variable becomes an array indexed by file descriptor, allowing independent leftover tracking per fd.
- Static variables in C — GeeksforGeeks
- File descriptors — Linux man pages (
man 2 read) - Understanding
read()system call - 42 Norm documentation
AI was used to help structure and write this README file. The logic, implementation, and understanding of the project were developed independently through personal reasoning and peer exchanges, in accordance with the 42 AI guidelines.