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

耗尽温柔 提交于 2020-01-14 14:57:15

问题


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!


回答1:


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!




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/12539488/determine-64-bit-file-size-in-c-on-mingw-32-bit

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