How can I get a file's size in C?

Nino picture Nino · Oct 26, 2008 · Viewed 825.9k times · Source

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 allocate using malloc(). Just writing malloc(10000*sizeof(char)); is IMHO a bad idea.

Answer

Rob Walker picture Rob Walker · Oct 26, 2008

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);