How am I supposed to read long input using fgets()
, I don't quite get it.
I wrote this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[10];
char *input;
while (fgets(buffer,10,stdin)){
input = malloc(strlen(buffer)*sizeof(char));
strcpy(input,buffer);
}
printf("%s [%d]",input, (int)strlen(input));
free(input);
return 0;
}
This is about the minimal set of changes that will give you the complete line of input. This grows the space by up to 9 bytes at a time; that isn't the best way to do it, but there's extra bookkeeping involved doing it the better ways (doubling the space allocated, and keeping a record of how much is allocated vs how much is in use). Note that
cur_len
record the length of the string in the space pointed to byinput
excluding the terminal null. Also note that the use ofextra
avoids a memory leak on failure to allocate.The
strcpy()
operation could be legitimately replaced bymemmove(input + cur_len, buffer, buf_len + 1)
(and in this context, you could usememcpy()
instead ofmemmove()
, but it doesn't always work whilememmove()
does always work, so it is more reliable to usememmove()
).With length-doubling — the
cur_max
variable records how much space is allocated, andcur_len
records how much space is in use.A better approach is to use an input mechanism that will allocate for you such as
getline
(or evenscanf
). (Note:scanf
does not allocate in all compilers. It does ingcc/Linux
, but does not withWindows/Codeblocks/gcc
)output:
getline example