如何为从c中的文件读取的一行文本分配足够的内存 [英] How can I allocate just enough memory for one line of text read from a file in c

查看:88
本文介绍了如何为从c中的文件读取的一行文本分配足够的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写程序的目的是,它将仅一次从文件中读取一行(这意味着当您读取一次后,您不应该返回该文件并再次读取),并且应该将该行存储在一个char数组中.数组的大小必须足够大以容纳文本行.此外,建议不要使用getchar,而应使用fgets.

The objective of my program that I need to write is that it will read in a line from a file ONLY ONCE (meaning when you read it once you should not go back to the file and read it again), and it should store that line in an array of chars. The size of the array must be just big enough to hold the line of text in. Also, it is recommended to not use getchar, and instead use fgets.

推荐答案

fget()周围循环,直到返回NULL并且feof()为true或读取的数据以\n结尾.对于每次迭代,将数据读入临时缓冲区并将其附加到最终缓冲区中,该缓冲区的大小会相应增加.

Loop around fget() until NULL is returned and feof() is true or the data read ends with a \n. For each iteration read in the data into a temporary buffer and append it to a final buffer, which is increased in size accordingly.

这篇关于如何为从c中的文件读取的一行文本分配足够的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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