Code:
#include <stdio.h>
#define MYGETS_BASESIZE 8
char *mygets(char *buffer)
{
int s=0, l=0;
do /* read a long line in small pieces */
{
s+=MYGETS_BASESIZE;
buffer=(char *)realloc(buffer, s);
fgets(&buffer[l], s-l, stdin);
l+=strlen(&buffer[l]);
}
while(buffer[l-1]!='\n');
buffer[l-1]='\0';
buffer=(char *)realloc(buffer, l);
return buffer;
}
main()
{
char *input;
/* read first line */
input=mygets(NULL);
printf("first line: %s\n", input);
/* read another line, 'overwriting' the first line */
input=mygets(input);
printf("second line: %s\n", input);
/* free malloc'ed memory */
free(input);
}
The mygets function automatically adjusts the string to the right size. This also means that you cannot use a static buffer as argument to this function, and that you are responsible for freeing the allocated memory!