A 42 school project that implements a function to read a line from a file descriptor. This function reads from a file descriptor line by line, making it easier to process text files or input streams.
The get_next_line function reads a line from a file descriptor and returns it, handling memory efficiently. A line is considered a string of characters terminated by a newline (\n) or the end of file (EOF).
char *get_next_line(int fd);fd: The file descriptor to read from
- Returns the line that was read (including the terminating
\ncharacter if present) - Returns NULL if there is nothing else to read or if an error occurred
- Reads from any valid file descriptor
- Works with both files and standard input
- Handles different buffer sizes through the BUFFER_SIZE define
- Memory efficient with proper memory allocation and deallocation
- No memory leaks
- Handles errors gracefully
get_next_line.c: Main function implementationget_next_line_utils.c: Helper functionsget_next_line.h: Header file with prototypes and includes
ft_strlen: Calculate string lengthconcat_str: Concatenate strings with specified lengthset_zero: Initialize memory to zeroreset_str_sta: Reset static string buffer
The project should be compiled with the following flags:
cc -Wall -Wextra -Werror -D BUFFER_SIZE=42 get_next_line.c get_next_line_utils.cThe BUFFER_SIZE can be modified to any positive value. The project is designed to work efficiently with various buffer sizes.
#include "get_next_line.h"
#include <fcntl.h>
int main(void)
{
int fd;
char *line;
fd = open("test.txt", O_RDONLY);
while ((line = get_next_line(fd)) != NULL)
{
printf("%s", line);
free(line);
}
close(fd);
return (0);
}- Does not handle binary files
- Uses one static variable to maintain the state between function calls
- File descriptor must be valid and readable
- BUFFER_SIZE must be greater than 0
maarjona (< [email protected]>)
This project is part of the 42 school curriculum.