【问题标题】:error opening file for reading: Value too large for defined data type打开文件读取时出错:对于定义的数据类型,值太大
【发布时间】:2014-04-29 17:28:34
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <iostream>
using namespace std;


#define FILEPATH "file.txt"
#define NUMINTS  (268435455)
#define FILESIZE (NUMINTS * sizeof(int))

int main()
{
    int i=sizeof(int);
    int fd;
    double *map;   //mmapped array of int's
  fd = open(FILEPATH, O_RDONLY);
    if (fd == -1) {
    perror("Error opening file for reading");
    exit(EXIT_FAILURE);
    }



    map = (double*)mmap(0, FILESIZE, PROT_READ, MAP_SHARED, fd, 0);
    if (map == MAP_FAILED) {
    close(fd);
    perror("Error mmapping the file");
    exit(EXIT_FAILURE);
    }

    for (i = 100000; i <=100100; ++i) {
    cout<<map[i]<<endl;
    }

    if (munmap(map, FILESIZE) == -1) {
    perror("Error un-mmapping the file");

    }
close(fd);
    return 0;
}

我收到文件大小太大的错误。

【问题讨论】:

  • 复制/粘贴确切的错误消息,格式化为代码(使用编辑框左上方的{} 工具)是诊断问题的更好证据。考虑使用该信息更新您的问题。祝你好运。
  • 文件在哪个FS上?
  • 文件包含从 0 到 268435455 的整数
  • 你是怎么编译的?你有 32 位还是 64 位操作系统?当前目录的文件系统 (FS) 是什么?
  • 这是编译错误还是运行时错误?这听起来像是一个编译文件,尽管映射一个近 2 GB 的文件在运行时也可能有点挑战。您系统上 size_t 的最大范围是多少?

标签: c linux


【解决方案1】:

您应该检查您的mmap-ed 文件是否足够大。

并确保FILESIZEint64_t 号码(您需要#include &lt;stdint.h&gt;):

#define FILESIZE ((int64_t)NUMINTS * sizeof(int))

在您的mmap 调用之前和成功的open 之后,使用fstat(2) 添加以下代码:

struct stat st={0};
if (fstat(fd, &st)) { perror("fstat"); exit (EXIT_FAILURE); };
if ((int64_t)st.st_size < FILESIZE) {
  fprintf(stderr, "file %s has size %lld but need %lld bytes\n",
          FILEPATH, (long long) st.st_size, (long long) FILESIZE);
  exit(EXIT_FAILURE);
}

最后,使用g++ -Wall -g 编译您的程序并使用gdb 调试器。此外,strace(1) 可能很有用。并确保当前目录的文件系统可以处理大文件。

您可能想要或需要定义_LARGEFILE64_SOURCE(和/或_GNU_SOURCE),例如用 g++ -Wall -g -D_LARGEFILE64_SOURCE=1 编译;见lseek64(3) & feature_test_macros(7)

附录

谷歌搜索

Value too large for defined data type 

很快就给出了this coreutils FAQ 的详细解释。您可能应该安装 64 位 Linux 发行版(或至少重新编译您的 coreutils 适当配置,或使用不同的文件系统...)

【讨论】:

  • 感谢您的宝贵时间,但此代码给出错误 fstat bad file descriptor
  • 这意味着open 失败了!或者一些奇怪的东西覆盖了fd
  • 我解决了这个问题,但现在我收到错误文件大小为 0 但需要 1073741820 字节
  • 这很好解释:你的文件是空的!您需要运行一些其他程序来填充它。
  • 感谢您抽出宝贵时间,但不幸的是发生了同样的错误 {Error opening file for reading: Value too large for defined data type }
【解决方案2】:

当我试图处理一个 2,626,351,763 字节的文件时(它不适合有符号的 32 位整数),我遇到了这个问题。当我使用 cc -m64 重新编译我的程序时,问题就消失了(我使用的是 Sun C 5.13 SunOS_sparc 2014/10/20 编译器)。

64 位系统很乐意处理大(>2^32 字节)文件,但如果应用程序是在 32 位模式下编译的,就没有那么多了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多