What should be incredible simple has me stumped. All I am doing is writing a getLine
method that should read a line into a buffer. I allocate memory to the buffer starting at 10 bytes
, then fgets
into a char array. The idea is that I attempt this over and over, doubling the size of the buffer, until it gets the whole line. However what I seem to be observing is that it reads a portion of the line, and then on the next attempt continues where it ran out of room on the last attempt, so it gives the last part of the line. Any insight it to what is wrong, I expect with my realloc
memory to the buffer, would be much appreciated.
char * mygetline( char **buffer, FILE * infile )
{
int buffSiz = 10;
*buffer = calloc( buffSiz, 1 );
do
{
char * result = fgets(*buffer, sizeof *buffer ,infile);
if(result == NULL)
{
free(buffer);
return NULL;
}
if(strchr(*buffer, '\n'))
return *buffer;
else
{
char *newBuf;
buffSiz = buffSiz*2;
newBuf = realloc(NULL, buffSiz);
char *buffer = newBuf;
printf("%d", buffSiz);
printf("%s", *buffer);
}
} while (1); // INFINITE LOOP - WE ONLY GET OUT BY RETURNING FROM WITHIN