c - 打开文件读取时出错 : Value too large for defined data type

标签 c linux

#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;
}

我收到文件大小过大的错误消息。

最佳答案

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

并确保FILESIZEint64_t号码(你需要 #include <stdint.h> ):

#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,或者使用不同的文件系统...)

关于c - 打开文件读取时出错 : Value too large for defined data type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371403/

相关文章:

c - 何时使用互斥量,何时不使用

linux - bash 脚本中的十六进制比较

linux - ptrace 能否判断 x86 系统调用使用的是 64 位还是 32 位 ABI?

linux - UC首先递归所有文件

php - 从当前目录下的 php 文件执行 git commit

使用 C 创建 SQLite3 表,但得到一个空数据库文件

c - 如何获取存储在数组中的字符串长度 (C)

c++ - llvm-ld 仍然存在于 clang 3.4 吗?

c - 有没有办法将 EOF 发送到读取消息队列的进程?

linux - 适用于 CentOs 7 的 Beanstalkd