stat64在64位Ubuntu上返回32位的st_size

3
unsigned char *map_file(char *filename, uint64_t *len) {
uint64_t fd = open64(filename, O_RDONLY);

struct stat64 st;
fstat64(fd, &st)

unsigned char *map;
map = (unsigned char *)mmap64(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);

对于大文件(我正在测试8.7 GB的文件),st.st_size最终会变为4294967295,这会导致分段错误(在47%处)。机器是64位的,操作系统(Ubuntu)也是64位的。我做错了什么?

3个回答

3
您可能需要定义这些宏之一。 http://www.kernel.org/doc/man-pages/online/pages/man7/feature_test_macros.7.html
  _LARGEFILE64_SOURCE
          Expose definitions for the alternative API specified by the LFS (Large
          File Summit) as a "transitional extension" to the Single UNIX
          Specification.  (See http://opengroup.org/platform/lfs.html.)  The
          alternative API consists of a set of new objects (i.e., functions and
          types) whose names are suffixed with "64" (e.g., off64_t versus off_t,
          lseek64() versus lseek(), etc.).  New programs should not employ this
          interface; instead _FILE_OFFSET_BITS=64 should be employed.

  _FILE_OFFSET_BITS
          Defining this macro with the value 64 automatically converts references
          to 32-bit functions and data types related to file I/O and file system
          operations into references to their 64-bit counterparts.  This is
          useful for performing I/O on large files (> 2 Gigabytes) on 32-bit
          systems.  (Defining this macro permits correctly written programs to
          use large files with only a recompilation being required.)  64-bit
          systems naturally permit file sizes greater than 2 Gigabytes, and on
          those systems this macro has no effect.

0

您不应该使用任何这些函数的*64()版本。在64位Linux上,off_t是64位的,并且一直都是。只需使用:

    int fd = open(filename, O_RDONLY);
    struct stat st;
    unsigned char *map;

    fstat(fd, &st);
    map = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);

(当然,带有错误检查)。我已经测试了上面的代码,使用了一个 >8GB 的文件,它可以正常运行。

0
尝试在编译行中添加-D_FILE_OFFSET_BITS=64

我正在使用“#define _FILE_OFFSET_BITS 64”。这两者之间有什么区别吗? - Chris
如果您使用#define,则必须确保在使用它的任何#includes之前定义它。否则我不知道会有什么区别。 - Karl Bielefeldt
我的所有定义都在包含语句之前,但感谢您的建议,非常有用。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接