fgets(linebuffer,maxlinelen,fp)
reads and stores at most maxlinelen - 1
characters in linebuffer
and 0-terminates it. Thus
if(strlen(linebuffer)==maxlinelen)
is never satisfied, strlen(linebuffer)
can be at most maxlinelen - 1
. Change the condition, and you will see that maxlinelen
increases if the file contains long lines (unless realloc
fails).
Your current code will however count the partial line read in as an entire line then, and read the next chunk of the line as a new line. To grow the buffer until the entire line fits in, you must continue reading from the file before collecting the line length and incrementing the line count. But we must check whether a full line (including the newline at the end) was read in case fgets
reads the maximal allowed number of char
s before enlarging the buffer, or we'd concatenate the following line and count two (or in freak cases even more) lines as one.
while((fgets(linebuffer,maxlinelen,fp))!=NULL)
{
while((strlen(linebuffer) == maxlinelen-1) && (linebuffer[maxlinelen-2] != '
'))
{
maxlinelen*=2;
linebuffer=realloc(linebuffer,maxlinelen * sizeof(char));
if(linebuffer==NULL)
{
printf("Error occurred reallocating space for linebuffer");
exit(1);
}
fgets(linebuffer + (maxlinelen/2 - 1), maxlinelen/2 + 1, fp);
}
would be a (rather inefficient, due to the strlen
calls) way to do that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…