## Struct stat and stat()

I came across this useful bit of code when wanting to read in some data from a text file. Suppose you do not know in advance how much data there is in a text file, how long should you make your buffer array to read the data into? The problem is you don’t know. You don’t want to make your buffer array neither too short and miss data, nor needlessly large.

You can use the stat() function to populate a structure containing information about a file, including its size, which you can then use to dynamically allocate memory. Here’s some example code:

#include
#include
#include
#include

int main(void){
FILE *fp;
char *buffer;
struct stat statistics;
fp = fopen("test.txt", "rb");
stat("test.txt", &statistics);
buffer = (char *) malloc(statistics.st_size);