OldWildWeb Logo

Get size of very large file in C - Example

How to get the size of a very large file C Linux


Example of how get the size of very large file in C Linux, with GCC


Working with large files can be a bit tricky under Linux with C due to the lack of documentation. I had some problem with the large file support topic so I decided to provide some examples on working with large files under C Linux, there are no standard functions and for this reason the code portability is not achievable.
In this example below we use the define _LARGEFILE64_SOURCE to enable the large file support on GCC, after that we use the 64 bit versions of the functions fopen -> fopen64, ftell -> ftello64, fseek -> fseeko64, to open the file, get the file pointer, set the file pointer at the end of the file and finally getting the file size.

The function use uses the __off64_t data type that is basically a 8 byte signed integer, could be replaced with long long int in almost all architectures.

//enables the large file support on GCC, must be defined before the includes
#define _LARGEFILE64_SOURCE
#include "stdio.h""
#include "stdlib.h"
#include "string.h"
__off64_t FILE_GetFileSizeFromPath(char *TheFileName);
__off64_t FILE_GetFileSizeFromPath(char *TheFileName)
{
__off64_t Prev = 0, TheFileSize = 0;
FILE *TheFilePointer = fopen64(TheFileName, "rb");
Prev = ftello64(TheFilePointer);
fseeko64(TheFilePointer, 0, SEEK_END);
TheFileSize = ftello64(TheFilePointer);
fseeko64(TheFilePointer, Prev, SEEK_SET);
fclose(TheFilePointer);
return TheFileSize;
}
int main(int argc, char** argv)
{
__off64_t theSize = 0;
theSize = FILE_GetFileSizeFromPath("/path/to/theLargeFile");
printf("\nSize : %lld ", theSize);
return (EXIT_SUCCESS);
}
Output example:
Size : 10565296876



Get size of a large file in C