如何使用与fgets如果您不知道的字符数被读? [英] How to use fgets if you don't know the number of characters to be read?

查看:384
本文介绍了如何使用与fgets如果您不知道的字符数被读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读的文件,并从它发送的文本字符串,所以我可以解析它。但是,该程序将不知道该文件是究竟有多长,所以你会怎么做,如果我想使用与fgets(),还是有更好的选择?

请注意:

 字符*与fgets(的char * str中,为size_t NUM,FILE *流);


解决方案

不要忘了的 与fgets() 每次读取一行,受有足够的空间。

人类很少写长于线... 80,256,挑一些...字符。 POSIX建议4096的线路长度所以,我通常使用:

 字符缓冲区[4096];而(与fgets(缓冲区,缓冲区尺寸,FP))
{
    ...工艺生产线......
}

如果你担心有人会在单行提供超过4K的数据(和机器生成的文件,如HTML或JSON,可能包含),那么你必须决定下一步做什么。你可以做任何以下的(也有可能我还没有提到的一些其他选项):


  1. 过程的超长线位,而不假设有在中间换行。

  2. 分配内存较长线(比如8K下手),更多的数据复制初始4K到分配的缓冲区,并读入缓冲区的后半部分,迭代直到找到行的末尾。
  3. 使用POSIX 2008功能 函数getline() 这是可以在Linux上。它的内存分配给你的。

I need to read a file and send the text from it to a string so I can parse it. However, the program won't know exactly how long the file is, so what would I do if I wanted to use fgets(), or is there a better alternative?

Note:

char *fgets(char *str, size_t num, FILE *stream);

解决方案

Don't forget that fgets() reads a line at a time, subject to having enough space.

Humans seldom write lines longer than ... 80, 256, pick a number ... characters. POSIX suggests a line length of 4096. So, I usually use:

char buffer[4096];

while (fgets(buffer, sizeof(buffer), fp)) 
{
    ...process line...
}

If you are worried that someone might provide more than 4K of data in a single line (and a machine generated file, such as HTML or JSON, might contain that), then you have to decide what to do next. You can do any of the following (and there are likely some other options I've not mentioned):

  1. Process the over-long lines in bits without assuming that there was a newline in between.
  2. Allocate memory for a longer line (say 8K to start with), copy the initial 4K into the allocated buffer, and read more data into the second half of the buffer, iterating until you find the end of line.
  3. Use the POSIX 2008 function getline() which is available on Linux. It does memory allocation for you.

这篇关于如何使用与fgets如果您不知道的字符数被读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆