I wanted to write a program in C that will accept a line of any length from stdin and display it or apply any function to that string. For this to work I will need a String (char []) with dynamic length.
This is how I did it:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
char *line;
line = malloc(10);
line[0] = '\0';
char *str = malloc(10);
fprintf(stdout, "Please enter your line:\n");
while(fgets(str, 10, stdin)){
//check for line break
if(str[strlen(str)-1] == '\n'){
str[strlen(str) - 1] = '\0';
strcat(line, str);
break;
}
strcat(line, str);
line = realloc(line, strlen(line) + 10);
str = realloc(str, strlen(str) + 10);
}
fprintf(stderr, "you entered %s\n", line);
//just for testing
/*
fprintf(stderr, "\n str= %s \n", str );
fprintf(stderr, "\n line= %s \n", line);
*/
free(line);
free(str);
exit(EXIT_SUCCESS);
}
However, this looks awful. I need two char arrays. In char *str I will write input from stdin and concatenate it to char *line. str will only hold up to 10Bytes of chars and because of that I need to concatenate everything to line.
Is there a cleaner way to save the output from stdin in this case and apply some function on it? Am I doing this wrong? Can it be done without malloc and realloc?
realloc(str), you never read more than 10 bytes at a time, you can just definestraschar str[10].strbe a power of 2, like1024, orBUFSIZEbecause CPU's like that.reallocwill returnNULL).mallocandreallocin case they fail.