This project has been created as part of the 42 curriculum by spopa.
The Get Next Line project involves programming a function that returns a line read from a file descriptor. This project introduces the concept of static variables in C and allows for reading content from a file (or standard input) line by line, regardless of the buffer size defined at compilation.
The project is compiled as a C library component. To test the function, you must compile it with a main.c file.
Use the following command, where BUFFER_SIZE can be modified to test different buffer lengths:
cc -Wall -Wextra -Werror -D BUFFER_SIZE=42 get_next_line.c get_next_line_utils.c main.c -o gnlFor the bonus part (handling multiple file descriptors):
cc -Wall -Wextra -Werror -D BUFFER_SIZE=42 get_next_line_bonus.c get_next_line_utils_bonus.c main_bonus.c -o gnl_bonusExecution: Run the executable passing a file as an argument (if your main supports it) or simply run:
./gnlAlgorithm Justification The core logic relies on a static variable (stash) to persist data between function calls. This is necessary because read() might fetch more data than a single line, and we need to "remember" the remaining characters for the next call.
The algorithm proceeds in three main steps:
Read and Accumulate (read_to_stash): The function reads from the file descriptor into a temporary buffer. This buffer is repeatedly joined to the static stash until a newline character (\n) is found or the End Of File (EOF) is reached.
Extract Line (ft_extract_line): Once a newline is present in the stash, a new string is allocated to copy characters up to and including the newline. This string is the return value.
Clean Stash (ft_clean_stash): The remaining characters after the newline are moved to a new memory block, and the old stash is freed. This prepares the static variable for the next call.
Memory Management: Special care was taken to free memory in case of allocation failures during the read loop or stash cleaning to prevent memory leaks.
-
man 3 read -
man 3 malloc
- Understanding the logic required to implement the bonus part (array of static pointers) to handle multiple file descriptors.