简体   繁体   中英

fgets for unknown string length

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM