c-从文件中读取行
我是 c 的新手,但我想从文件中读取文本。我不知道文件第一行的长度,那么如何为fgets函数编写正确的参数呢? 现在我有:
char read[30]; // but I really don't know how long the line will be
while(fgets(read, sizeof(read), fp).......
I am new to c, but I would like to read in text from a file. I don't know the length of the first line of the file, so how can I write the correct parameters for the fgets function?
Right now I have:
char read[30]; // but I really don't know how long the line will be
while(fgets(read, sizeof(read), fp).......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您必须不断重新分配并附加到缓冲区,直到到达行尾。代码并不漂亮,但没有使用标准 C 库的简单替代方案:
You'll have to just keep reallocating and appending to a buffer until you reach the end of the line. The code isn't pretty, but there isn't a simple alternative using the standard C library:
如果你不知道你的最大。 linesize 你可以逐个字符读取并使用 realloc,那么就很简单:
If you don't know your max. linesize you can read char by char and use realloc, then it's easy:
您必须为该线设置一个安全合理的最大长度并使用它。
You have to set a safe reasonable maximum length for the line and use it.
使用 C 标准库,您只需要接受一些最大行大小并遵循它即可。如果您检测到
read
不以换行符结尾,您可以读取更多内容并附加附加数据,直到找到行尾。然而,对于大多数可以接受 fgets() 进行解析的应用程序来说,固定的行长度也是可以接受的。Using the C standard library you will just have to accept some maximum line size there and go with it. If you detect that
read
does not end in a newline you could read more and append the additional data until you find the end of a line. However, for most applications wherefgets()
is acceptable for parsing, a fixed line length is also acceptable.你的 fgets() 中有一个关闭。如果您的缓冲区大小为 30,则需要使用 sizeof(read)+1。就像菲利斯所说,你需要设置一个安全的最大值。
There's an off by one in your fgets(). If your buffer has a size of 30, you need to use sizeof(read)+1. Like Felice said, you'll need to set a safe maximum.
你有(至少)两个选择。到目前为止,最常见的方法是分配一个假定“足够大”(例如,几千字节)的缓冲区,然后就使用它(如果提供的数据不符合该限制,则很可能会出现错误行为)。
主要的替代方法是动态为缓冲区分配内存,当/如果您读取的数据不适合时,请使用 realloc 增加缓冲区大小并读取更多数据。
You have (at least) two choices. By far the most common is to allocate a buffer assumed to be "big enough" (e.g., a couple of kilobytes) and just go with it (and quite possibly mis-behave if provided with data that doesn't fit that limitation).
The primary alternative is to allocate the memory for the buffer dynamically, and when/if that data you read doesn't fit, use
realloc
to increase the buffer size and read some more.