Before anyone complains of "duplicate", I've been checking SO quite thoroughly, but there seem to be no clean answer yet, although the question looks quite simple.
I'm looking for a portable C code, which is able to provide the size of a file, even if such a file is bigger than 4GB.
The usual method (fseek, ftell) works fine, as long as the file remains < 2GB. It's fairly well supported everywhere, so I'm trying to find something equivalent.
Unfortunately, the updated methods (fseeko, ftello) are not supported by all compilers. For example, MinGW miss it (and obviously MSVC). Furthermore, some comments make me believe that the new return type (off_t) does not necessarily support size > 2GB, it may depend on some external parameters, to be checked.
The unambiguous methods (fseeko64, ftello64) are not supported by MSVC. MS provides their equivalent, _fseeki64 & _ftelli64. This is already bad, but it becomes worse : some Linux configurations seem to badly support these functions during run time. For example, my Debian Squeeze on PowerPC, using GCC 4.4, will produce a "filesize" method using fseeko64 which always return 0 (while it works fine for Ubuntu64). MinGW seems to answer some random garbage above 2GB.
Well, I'm a bit clueless as far as portability is concerned. And if I need to make a bunch of #if #else, then why not go straight to the OS & compilers specifics methods in the first place, such as GetFileSize() for MSVC for example.
Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
What we need is to open the terminal and type du -sh file name in the prompt. The file size will be listed on the first column. The size will be displayed in Human Readable Format. This means we can see file sizes in Bytes, Kilobytes, Megabytes, Gigabytes, etc.
int ch;
FILE *f = fopen("file_to_analyse", "rb");
/* error checking ommited for brevity */
unsigned long long filesize = 0; /* or unsigned long for C89 compatability*/
while ((ch = fgetc(f)) != EOF) filesize++;
fclose(f);
/* error checking ommited for brevity */
You said it: there's no portable method; if I were you I'd just go with GetFileSize
on Windows and stat
on POSIX.
You should be able to use stat64
on Linux and _stat64
on Windows to get file size information for files over 2 GBs, and both functions are very similar in usage. You can also use a couple of #define
s to use stat64
on Windows too:
#if __WIN32__
#define stat64 _stat64
#endif
However, although this should work, it should be noted that the _stat
family of functions on Windows is really just a wrapper around other functions, and will add additonal resources and time overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With