C fgets与fgetc的阅读线 [英] C fgets versus fgetc for reading line

查看:220
本文介绍了C fgets与fgetc的阅读线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取一行文本(以换行符结尾),而不对长度做出假设。所以我现在面对各种可能性:

I need to read a line of text (terminated by a newline) without making assumptions about the length. So I now face to possibilities:


  • 使用 fgets 并每次检查是否最后一个字符是换行符并连续附加到缓冲区

  • 使用 fgetc 读取每个字符,偶尔 realloc 缓冲区

  • Use fgets and check each time if the last character is a newline and continuously append to a buffer
  • Read each character using fgetc and occasionally realloc the buffer

Intuition告诉我 fgetc 变体可能会慢一些,但是我再也看不到 fgets 如何在不检查每个角色的情况下做到这一点(我的直觉也不总是那么好)。线条非常大,因此性能很重要。

Intuition tells me the fgetc variant might be slower, but then again I don't see how fgets can do it without examining every character (also my intuition isn't always that good). The lines are quite large so the performance is important.

我想知道每种方法的优缺点。提前谢谢。

I would like to know the pros and cons of each approach. Thank you in advance.

推荐答案

我建议使用 fgets()耦合使用动态内存分配 - 或者您可以调查 getline的界面() ,它符合POSIX 2008标准,可在更新的Linux机器上使用。这为你做了内存分配。您需要密切关注缓冲区长度及其地址 - 因此您甚至可以创建一个处理信息的结构。

I suggest using fgets() coupled with dynamic memory allocation - or you can investigate the interface to getline() that is in the POSIX 2008 standard and available on more recent Linux machines. That does the memory allocation stuff for you. You need to keep tabs on the buffer length as well as its address - so you might even create yourself a structure to handle the information.

虽然 fgetc()也有效,它有点吝啬 - 但只是略有不同。在封面下,它使用与 fgets()相同的机制。内部可能能够利用更快的操作 - 类似于 strchr() - 当您调用 fgetc()直接。

Although fgetc() also works, it is marginally fiddlier - but only marginally so. Underneath the covers, it uses the same mechanisms as fgets(). The internals may be able to exploit speedier operation - analogous to strchr() - that are not available when you call fgetc() directly.

这篇关于C fgets与fgetc的阅读线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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