我得到了一些我需要解析的大文件,而且人们一直在推荐mmap,因为这应该避免必须在内存中分配整个文件。mmap问题,分配大量内存
但看着'顶部'它看起来好像我打开整个文件到内存中,所以我认为我必须做错了什么。 '热门节目> 2.1演出'
这是一个代码片断,显示我在做什么。
感谢
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <fcntl.h>
#include <sysexits.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <cstring>
int main (int argc, char *argv[]) {
struct stat sb;
char *p,*q;
//open filedescriptor
int fd = open (argv[1], O_RDONLY);
//initialize a stat for getting the filesize
if (fstat (fd, &sb) == -1) {
perror ("fstat");
return 1;
}
//do the actual mmap, and keep pointer to the first element
p =(char *) mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
q=p;
//something went wrong
if (p == MAP_FAILED) {
perror ("mmap");
return 1;
}
//lets just count the number of lines
size_t numlines=0;
while(*p++!='\0')
if(*p=='\n')
numlines++;
fprintf(stderr,"numlines:%lu\n",numlines);
//unmap it
if (munmap (q, sb.st_size) == -1) {
perror ("munmap");
return 1;
}
if (close (fd) == -1) {
perror ("close");
return 1;
}
return 0;
}
@monkeyking,code-pre的正确关闭是/ pre/code,不是post :-)修复了代码标签。 – paxdiablo 2009-12-29 03:34:34
啊,万分感谢! #include我不能把它们放到代码示例中 – monkeyking 2009-12-29 03:37:54
标记整个块然后使用CTRL-K - 这会缩进四个空格。我现在已经这样做了,你应该可以看到一个stdio包含。 – paxdiablo 2009-12-29 03:44:06