Don't forget that fgets()
reads a line at a time, subject to having enough space.
Humans seldom write lines longer than ... 80, 256, pick a number ... characters. POSIX suggests a line length of 4096. So, I usually use:
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp))
{
...process line...
}
If you are worried that someone might provide more than 4K of data in a single line (and a machine generated file, such as HTML or Javascript, might contain that), then you have to decide what to do next. You can do any of the following (and there are likely some other options I've not mentioned):
- Process the over-long lines in bits without assuming that there was a newline in between.
- Allocate memory for a longer line (say 8K to start with), copy the initial 4K into the allocated buffer, and read more data into the second half of the buffer, iterating until you find the end of line.
- Use the POSIX 2008 function
getline()
which is available on Linux. It does memory allocation for you.