Search code examples
cmingwfilesize

Determine 64-bit file size in C on MinGW 32-bit


I'm going crazy trying to get this to work in MinGW 32-bit. It works on all other platforms I've tried.

All I want to do is get the size of a > 4GB file into a 64-bit int.

This works fine on other platforms:

#define _FILE_OFFSET_BITS   64
#include <sys/stat.h>

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

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

    return -1; 
}

I tried adding the following defines before the above code, based on various suggestions I found online:

#define _LARGEFILE_SOURCE   1
#define _LARGEFILE64_SOURCE 1
#define __USE_LARGEFILE64   1

Also tried:

#ifdef __MINGW32__
#define off_t off64_t
#endif

And finally tried adding -D_FILE_OFFSET_BITS=64 to the gcc flags (should be the same as the above define though...)

No luck. The returned int64_t is still getting truncated to a 32-bit value.

What is the right way to determine a 64-bit file size in MinGW 32-bit?

Thanks!


Solution

  • Thanks guys, good suggestions but I figured it out... MinGW requires this define to enable the struct __stat64 and the function _stat64:

    #if __MINGW32__
    #define __MSVCRT_VERSION__ 0x0601
    #endif
    

    Then this works:

    int64_t fsize(const char *filename) {
    
    #if __MINGW32__
        struct __stat64 st; 
        if (_stat64(filename, &st) == 0)
    #else
        struct stat st; 
        if (stat(filename, &st) == 0)
    #endif
    
            return st.st_size;
    
        return -1; 
    }
    

    Hope this helps somebody.