3

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!

Jettoblack
  • 125
  • 3
  • 8

4 Answers4

5

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.

Jettoblack
  • 125
  • 3
  • 8
3

I don't have MinGW handy right now, but if I recall correctly there is a _stat64 function what uses a struct __stat64. You will probably want to hide this ugliness with some cunning macros!

idz
  • 12,825
  • 1
  • 29
  • 40
  • There's probably no need to get too cunning - just an `#if _WIN32/#else/#endif` in the `fsize()` function. – Michael Burr Sep 22 '12 at 05:15
  • @MichaelBurr As long as `fsize()` is the only place he/she uses `stat`. (When I typed cunning my tongue was firmly in my cheek!) – idz Sep 22 '12 at 09:17
  • This works but _stat64 is only available in MinGW if you add this before #include , otherwise the stat64 symbols won't resolve: #define __MSVCRT_VERSION__ 0x0601 – Jettoblack Sep 25 '12 at 18:36
0

You can try lseek64 if that exists in the MinGW package

   #define _LARGEFILE64_SOURCE     /* See feature_test_macros(7) */
   #include <sys/types.h>
   #include <unistd.h>

   off64_t lseek64(int fd, off64_t offset, int whence);
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
0

You can call the Windows API GetFileSizeEx to get the file size for an open handle, or GetFileAttributesEx A/W for a filename.

For a working example see https://stackoverflow.com/a/8991228/1505939 .

M.M
  • 138,810
  • 21
  • 208
  • 365