If you are using Linux you should probably use
getline()[
^] instead of
fgets()
. getline() reads and allocates a buffer, and returns the number of characters read. This means that there's no need to try to calculate the length of the buffer, and/or test the last character in the buffer to determine if its a newline or not
#include <stdio.h>
#include <stdlib.h>
char *buff = NULL;
size_t bufflen = 0;
ssize_t rlen;
while( (rlen = getline(&buff, &bufflen, input) > 0 ) {
buff[rlen] = '\0';
}
free(buff);
The
bufflen
parameter to getline() is the current allocated size of the buffer, which getline uses to reallocate only when necessary. An informal test shows that getline() to be about 30% faster than using fgets() and strlen().