get_next_line

This function reads line by line from an fd (file descriptor). It uses a static buffer (stored) to save remaining text between calls, allowing it to handle partial lines across multiple reads. The my_line function extracts a complete line, and re_adj_storage adjusts the buffer for the next call.


Key Considerations

  1. Memory Management: Each function frees dynamic variables when they are no longer used, minimizing memory leaks.
  2. Error Handling: Checks file accessibility and BUFFER_SIZE validity, returning NULL if anything fails.
  3. Static Storage: stored is a static variable that persists between get_next_line calls, enabling continuous line reading.

Core Functions

Below is a description of each key function in the project:

Function Description
get_next_line(int fd) Main function controlling the read flow. Verifies the file and calls other functions.
read_join(char *stored, int fd) Reads data from the file and stores it in stored.
initialize_stored(char *stored, char *read_bff) Initializes stored if NULL, preventing concatenation errors.
my_line(char *stored) Extracts a complete line from stored and returns it.
re_adj_storage(char *stored) Adjusts stored by removing the already-read line, preparing it for the next call.

To link your main to the function (gnl) for testing:

gcc main.c get_next_line.c get_next_line_utils.c -o p

Bonus: Multiple fd Reading

  • Implementation: Allows reading from multiple fds simultaneously without losing track of lines for each.
  • Key Modification:
    • Converts stored into a static array: static char *stored[65536].
    • Each fd has its own space in the array, enabling independent handling of multiple files.

Modified Code

char	*get_next_line(int fd)
{
	char			*line;
	static char		*stored[65536];

	if (fd < 0 || BUFFER_SIZE <= 0)
		return (NULL);
	stored[fd] = read_join(stored[fd], fd);
	if (!stored[fd])
		return (free(stored[fd]), NULL);
	line = my_line(stored[fd]);
	stored[fd] = re_adj_storage(stored[fd]);
	return (line);
}