This project has been created as part of the 42 curriculum by amarjan.
The get_next_line project consists of implementing a function that reads from a file descriptor and returns one line at a time.
Each call to the function returns the next line, including the newline character (\n)
if it exists, until the end of the file is reached.
This project helps understand how file descriptors, the read() function, memory
allocation, and static variables work in C.
Compile the project using the following flags:
cc -Wall -Wextra -Werror get_next_line.c get_next_line_utils.c main.cThis project provides a function, not a standalone program.
To test it, a small main.c can be written that:
-
opens a file and passes its file descriptor to
get_next_line, or -
uses file descriptor 0 to read from standard input.
The behavior of the function is independent of the test program used.
-
read()reads a fixed number of bytes defined byBUFFER_SIZE, not full lines. -
A static buffer (stash) is used to store data that has been read but not yet returned.
-
The function keeps reading and appending data until a newline
(\n)or EOF is found. -
One line is extracted and returned.
-
Any remaining data is preserved for the next call.
A static variable is required to avoid losing unread data between calls, especially when
a single read() call contains multiple lines.
The implementation works correctly for:
-
BUFFER_SIZE = 1 -
Large values of
BUFFER_SIZE -
Values larger than the file size
The algorithm does not rely on a specific buffer size.
-
man 2 read -
man 3 malloc -
man 3 free -
42
get_next_linesubject
AI tools were used to help understand concepts and edge cases.
while ((line = get_next_line(fd)) != NULL)
{
printf("%s", line);
free(line);
}