c - How to read input of unknown length using fgets -


how supposed read long input using fgets(), don't quite 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; } 

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main(void) {     char buffer[10];     char *input = 0;     size_t cur_len = 0;     while (fgets(buffer, sizeof(buffer), stdin) != 0)     {         size_t buf_len = strlen(buffer);         char *extra = realloc(input, buf_len + cur_len + 1);         if (extra == 0)             break;         input = extra;         strcpy(input + cur_len, buffer);         cur_len += buf_len;     }     printf("%s [%d]", input, (int)strlen(input));     free(input);     return 0; } 

this minimal set of changes give complete line of input. grows space 9 bytes @ time; isn't best way it, there's bookkeeping involved doing better ways (doubling space allocated, , keeping record of how allocated vs how in use). note cur_len record length of string in space pointed input excluding terminal null. note use of extra avoids memory leak on failure allocate.

the strcpy() operation legitimately replaced memmove(input + cur_len, buffer, buf_len + 1) (and in context, use memcpy() instead of memmove(), doesn't work while memmove() work, more reliable use memmove()).


with length-doubling — cur_max variable records how space allocated, , cur_len records how space in use.

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main(void) {     char buffer[10];     char *input = 0;     size_t cur_len = 0;     size_t cur_max = 0;     while (fgets(buffer, sizeof(buffer), stdin) != 0)     {         size_t buf_len = strlen(buffer);         if (cur_len + buf_len + 1 > cur_max)         {             size_t new_len = cur_max * 2 + 1;             if (buf_len + 1 > new_len)                 new_len = buf_len + 1;             char *extra = realloc(input, new_len);             if (extra == 0)                 break;             input = extra;             cur_max = new_len;         }         strcpy(input + cur_len, buffer);         cur_len += buf_len;     }     printf("%s [%d]", input, (int)strlen(input));     free(input);     return 0; } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -