Possible Duplicate:
How do you determine the size of a file in C?
How can I find out the size of a file? I opened with an application written in C.
I would like to know the size, because I want to put the content of the loaded file into a string, which I alloc using malloc()
. Just writing malloc(10000*sizeof(char));
is IMHO a bad idea.
How to use lseek/fseek/stat/fstat to get filesize ?
Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):
This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).
If you have the file descriptor
fstat()
returns a stat structure which contain the file size.You need to seek to the end of the file and then ask for the position:
You can then seek back, e.g.:
or (if seeking to go to the beginning)
HTH
If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.