There's a fundamental problem with read
function: It just reads any arbitrary bytes, doesn't differentiate on their values, thus doesn't recognise a newline either.
So on implementing the function you have handle the newlines being somewhere right in the middle of the data you just read from file. Additionally read doesn't necessarily read all the bytes that might fit into the buffer, so you might need to read once more to get an entire line.
Finally if no newline is encountered after filling the entire buffer you might need to re-allocate a larger buffer (you might want to ask if realloc
is allowed, too. In a first step you might just ignore this case, though, and provide a statically allocated buffer with some reasonable size, hoping you won't exceed that one...
This might look somewhat like:
static char buffer[1024];
static size_t length = 0;
for(;;)
{
// handle input
ssize_t n = read(fd, buffer + length, sizeof(buffer) - length);
if(n <= 0)
{
// something went wrong, handle appropriately;
// this includes the case of reaching the end of the file,
// in that specific case you'd return all the remaining buffer
// and on that begin empty a null pointer.
}
}
You might notice that this code handles the input before reading a new line – background is that you might have read more than one complete line at once, and you might no be looking for the next line still in the buffer!
So once you found a newline you'll allocate a new buffer for a string and copy the bytes from the beginning of the buffer up to the newline character found. Then you copy all the remaining bytes of the buffer towards front and read into the buffer starting right behind the bytes yet remaining.
Note that - as you rely on static (or alternatively global) variables – the function as is is not thread-safe. If that gets an issue you'll need to introduce some appropriate protection.