简体   繁体   English

未知字符串长度的fgets

[英]fgets for unknown string length

How can I read with fgets a string from keyboard buffer, of unknown length? 如何使用fgets从未知长度的键盘缓冲区读取字符串? *fgets(char *s, int size, FILE *stream);

Could I give fgets a NULL in the position of int size? 我可以在int大小的位置给fgets一个NULL吗?

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. 如果有,POSIX的getline()执行此操作。

The length argument of fgets is one of the reasons the function is "better" than gets . fgets的length参数是功能比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. 使用getline可能会导致malloc / realloc,如果使用动态内存没有问题,请随时使用该函数。 I prefer simple buffer[MAX_SIZE+1] variables. 我更喜欢简单的buffer[MAX_SIZE+1]变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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