Get Large File Size in C

半世苍凉 提交于 2019-11-29 09:55:53

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 #defines 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.

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 */

I have implemented and tested the following:

#if __WIN32__
#define stat64 _stat64
#endif

using MinGW64 gcc compiler 4.8.1 and Linux gcc 4.6.3 compiles and works.

On OSX, no redefinition of stat required.

for lstat and fstat functions I expect similar macro #defines to work.

alk

What about using lseek() (or _lseek()) with SEEK_END? It returns the offset sought to.

Under linux _FILE_OFFSET_BITS needs to be defined to 64 for lseek() to return 64bit values (which should be the default anyhow).

Roger
#include sys/stat.h

off_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!