#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 文件足够大。
并确保FILESIZE
是 int64_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/