fgets(linebuffer,maxlinelen,fp)
reads and saves no more than maxlinelen - 1 characters in linebuffer and 0-completes it. In this way,
if(strlen(linebuffer)==maxlinelen)
never executed, strlen(linebuffer) can be no more than maxlinelen - 1 . Change the condition and you will see that maxlinelen incremented if the file contains long lines (unless realloc is working).
Your current code, however, will count the partial line read as a whole line and read the next fragment of the line as a new line. To increase the buffer until the entire line has been entered, you must continue reading from the file before collecting the line length and increasing the number of lines. But we need to check whether the full line has been read (including the new line at the end), in case fgets reads the maximum char number before the buffer extension, or we will concatenate the next line and count two (or in fictitious cases even more) lines as one.
while((fgets(linebuffer,maxlinelen,fp))!=NULL) { while((strlen(linebuffer) == maxlinelen-1) && (linebuffer[maxlinelen-2] != '\n')) { 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 (rather inefficient due to strlen calls) for this.
source share