Context
Yesterday I talked to @dutenrapha, who answered
all my questions about get_next_line:
get_next_line is a function that reads an entire line from a file indexed by a file descriptor fd. It then alocates a string with the contents of that line without the linebreak '\n' and points line to it.
We don’t have to pass anything allocated to get_next_line, we just pass the address of a pointer that will point to the allocated string. line should be freeable with free() after the function call unless an error occured.
We will incrementally read the file with read(), which advances its position in the file descriptor automatically.
We need to use a static pointer as a read buffer to access what was read in previous calls.
We need to handle the following situations:
- If the read buffer doesn’t have a
'\n', we concatenate with the previous buffer and call read again. - If the read buffer has a
'\n', we concatenate with the previous buffer up to'\n'. - If we reach the end of the file (
read() == 0), we concatenate with the previous buffer. - We finally point
lineto an allocated string that contains the entire line without the'\n'. Then we release the memory allocated in the intermediate strings and return1or0for'\n'andend_of_filerespectively. - If the parameters have any problems (
BUFFER_SIZE <= 0), or if in any operation we were unable to allocate memory, we free whatever memory was allocated and return -1.
I also found this amazing documentation by @harm-smits.
Today I will not be able to code much because of work and driver’s ed.