Reputation: 167
How can I read with fgets
a string from keyboard buffer, of unknown length? *fgets(char *s, int size, FILE *stream);
Could I give fgets
a NULL
in the position of int
size?
Upvotes: 1
Views: 2966
Reputation: 22241
The length argument of fgets
is one of the reasons the function is "better" than gets
. You absolutely have to specify the amount of data the buffer you are passing can fit, otherwise your app may crash.
In most of my applications I simply use a buffer several times as long as it is required to fit whatever I expect to receive.
Using getline may cause a malloc/realloc, and if you have no problem with using dynamic memory feel free to use that function. I prefer simple buffer[MAX_SIZE+1]
variables.
Upvotes: 3
Reputation: 399703
No, you need to know what the line terminator is (newline and/or carriage return, typically), and keep reading in a loop until you get it. Of course, you also need to grow your buffer and copy each piece into it as you get them.
If you have it, POSIX' getline()
does this.
Upvotes: 7