问题
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.
回答1:
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.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/20277987/how-can-i-allocate-just-enough-memory-for-one-line-of-text-read-from-a-file-in-c