Since you want to read the entire file, the best way is to make a buffer the size of the file size. It makes no sense to resize the buffer when you go. It just harms performance for no good reason.
File size can be obtained in several ways. The quick and dirty way is to lseek() at the end of the file:
Another way is to get information using fstat() :
struct stat fileStat; fstat(fd, &fileStat); // Don't forget to check for an error return in real code // Allocate enough to hold the whole contents plus a '\0' char. char *buff = malloc(fileStat.st_size + 1);
To get all the necessary types and prototypes of functions, make sure you include the right header:
#include <sys/stat.h> // For fstat() #include <unistd.h> // For lseek()
Note that read() does not automatically end data with \0 . You need to do this manually, so we allocate an extra character (size + 1) for the buffer. The reason you already have the \0 character in your case is a random case.
Of course, since buf now a dynamically allocated array, remember to free it again when you no longer need it:
free(buff);
Remember that allocating a buffer the size of the file you want to read can be dangerous. Imagine that (by mistake or as intended, it does not matter) the file is several GB in size. For such cases, it is useful to have the maximum size allowed. However, if you do not want to use such restrictions, you should switch to another way of reading from files: mmap() . Using mmap() you can map parts of a file into memory. Thus, it doesn't matter how big the file is, since you can only work in parts, except that you control memory usage.
source share