[英]How can I allocate just enough memory for one line of text read from a file in c
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.
数组的大小必须足够大以容纳文本行。此外,建议不要使用getchar,而应使用fgets。
Worst case, there is only one line of text in the file, so you would need to get the file size and allocate that much memory for the buffer. 最坏的情况是,文件中只有一行文本,因此您需要获取文件大小并为缓冲区分配那么多的内存。
#include <io.h>
#include <stdlib.h>
long buffLen = _filelength(...);
// check bufLen for errors
char* buffer = (char*)malloc((size_t)buffLen);
// check for allocation failures (it could be an 8 gigabyte file)
If your CRT doesn't support the _filelength posix function, look through this thread , and also keep in mind that a long
isn't 64-bits on all platforms, so using a method that returns a 64-bit value is best. 如果您的CRT不支持_filelength posix函数,请仔细检查该线程 ,并记住在所有平台上
long
都不是64位,因此最好使用返回64位值的方法。
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
//this two function will help you,you can man them on linux
Loop around fget()
until NULL
is returned and feof()
is true or the data read ends with a \\n
. 循环
fget()
直到返回NULL
且feof()
为true或读取的数据以\\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. 对于每次迭代,将数据读入临时缓冲区并将其附加到最终缓冲区中,最终缓冲区的大小会相应增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.