I need to read a line of text (terminated by a newline) without making assumptions about the length. So I now face to possibilities:
- Use
fgets
and check each time if the last character is a newline and continuously append to a buffer - Read each character using
fgetc
and occasionallyrealloc
the buffer
Intuition tells me the fgetc
variant might be slower, but then again I don't see how fgets
can do it without examining every character (also my intuition isn't always that good). The lines are quite large so the performance is important.
I would like to know the pros and cons of each approach. Thank you in advance.
getline
function withfgets
is that it is impossible to handle null bytes and files not ending with a newline character at the same time. Iffgets
encounters an EOF condition and returns without a newline character, you can only assume that the string ends on the first null byte. (In other cases, you can dostrchr(buf, '\n')
to find out where the reading stopped—or if there is no'\n'
, you need torealloc
.) – Ostiary