This project is about implementing a function in C that reads a file line by line using a file descriptor. The function reads one line per call and preserves the input between calls using a static buffer. Our challanges were handling error management, memory allocation, static variables and buffer management efficiently in C.
- Reads one line including the newline
\n - Works with different
BUFFER_SIZEvalues - Returns
NULLif no more lines to read or on error - Handles different file descriptors (stdin, file descriptor, ...)
- Manages memory safely between successive calls
Contains the main logic. The function reads from the file descriptor and returns one line at a time.
Contains all the necessary helper functions (string operations, memory handling, etc.).
Header file that declares the function prototype and any required includes/macros.
Validates a file descriptor and returns the next full line (including a new line if it occurs).
Parameters:
int fd: File descriptor to read from file
Returns:
NULLif:- End-of-file is reached
- An error occurs (e.g., invalid
fd,readfailure, or memory allocation error)
- a dynamically allocated string containing the next line (including
\nif it exists)
Determines the end of a line, appends buffer content to the current line with the function new_line() and shifts remaining content with the function buffer_change() for future calls.
Parameters:
char *buffer: Buffer containing the input from fdchar *line: A dynamically allocated string containing the next line (including\nif it exists)
Returns:
- line with
\n
Appends one element from the buffer content to the current line.
Parameters:
char *line: the next linechar c: one element from the buffer
Returns:
- line with one char from buffer
Shifts remaining content for future calls.
Parameters:
char *buffer: old buffersize_t start: starting index of new buffer from old buffer
Returns:
- shifted buffer
| Function Name | Category | Parameters | Return |
|---|---|---|---|
ft_strlen |
String Utility | const char *s |
Length of the string (size_t) |
free_mem |
Memory/Error Handling | char *line, int bytesRead |
Always returns NULL (after free line) |
Compile the source files:
cc *.c -o get_next_lineThen you can execute like:
./get_next_line
You can use get_next_line in your source file.
#include <stdio.h>
#include <fcntl.h>
#include "get_next_line.h"
int main(void)
{
int fd = open("test", O_RDONLY);
char *line;
line = get_next_line(fd);
printf("1.line: %s", line);
free(line);
line = get_next_line(fd);
printf("2.line: %s", line);
free(line);
line = get_next_line(fd);
printf("3.line: %s", line);
free(line);
close(fd);
return (1);
}