I need to ask one more question about reading from the stdin. I am reading a huge trunk of lines from the stdin, but it is definitely unknown which is the size of every line. So I don't want to have a buffer like 50Mio just for a file having lines of three char and than a file using these 50 Mio per line. So at the moment I am having this code:
int cur_max = 2047;
char *str = malloc(sizeof(char) * cur_max);
int length = 0;
while(fgets(str, sizeof(str), stdin) != NULL) {
//do something with str
//for example printing
printf("%s",str);
}
free(str);
So I am using fgets for every line and I do have a first size of 2047 char per line. My plan is to increase the size of the buffer (str) when a line hits the limit. So my idea is to count the size with length and if the current length is bigger than cur_max then I am doubling the cur_max. The idea comes from here Read line from file without knowing the line length I am currently not sure how to do this with fgets because I think fgets is not doing this char by char so I don't know the moment when to increase the size.
getlinefunction.char *str, just what do you thinksizeof( str )returns?sizeof(str)->sizeof(char) * cur_max.sizeof(str)is the size of a pointer on your platform (most likely 4 or 8), not the size of the buffer where it points to. Remember: pointers are not arrays.sizeof(str)is the same assizeof(char *)which is probably either 4 or 8. You want something more likefgets(str, cur_max, stdin). See also stackoverflow.com/questions/44689288/… .