【发布时间】:2016-07-16 07:17:12
【问题描述】:
这是我的问题的描述:
我想使用 C 中的read 系统调用读取一个大约 6.3GB 的大文件到内存中,但出现错误。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
int main(int argc, char* argv[]) {
int _fd = open(argv[1], O_RDONLY, (mode_t) 0400);
if (_fd == -1)
return 1;
off_t size = lseek(_fd, 0, SEEK_END);
printf("total size: %lld\n", size);
lseek(_fd, 0, SEEK_SET);
char *buffer = malloc(size);
assert(buffer);
off_t total = 0;
ssize_t ret = read(_fd, buffer, size);
if (ret != size) {
printf("read fail, %lld, reason:%s\n", ret, strerror(errno));
printf("int max: %d\n", INT_MAX);
}
}
然后编译:
gcc read_test.c
然后运行:
./a.out bigfile
输出:
total size: 6685526352
read fail, 2147479552, reason:Success
int max: 2147483647
系统环境是
3.10.0_1-0-0-8 #1 SMP Thu Oct 29 13:04:32 CST 2015 x86_64 x86_64 x86_64 GNU/Linux
有两个地方我不明白:
- 读取大文件失败,但读取小文件失败。
- 即使有错误,似乎
errno设置不正确。
【问题讨论】:
-
很好,调用成功读取了
2147479552字节。你需要循环直到你消耗了所有的data.btw?你总共有多少内存? -
为什么?在少数情况下,您确实需要内存中的整个文件。
-
您的系统是否限制了可用内存?你试过
ulimit -s unlimited吗? -
如果你使用
open()和read()等POSIX函数,你也可以使用POSIXstat()和/或fstat()直接获取文件的大小。 -
根据您将这个巨大的文件存储在内存中后要如何处理它,
mmap可能比read更合适。
标签: c linux file-io posix unbuffered