mmap函数用来将文件映射进内存。需要指出的是这里的内存指的是虚拟内存。
mmap函数可以将一个文件的内容映射到内存,这样就可以直接对该内存进行操作,从而省去IO操作。
下面是一个小例子:
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char *argv[]){
? ? int fd,len;
? ? char *ptr;
? ? if(argc<2){
? ? ? ? printf("please enter a file\n");? ?
? ? ? ? return 0;
? ? }?
? ? if((fd=open(argv[1],O_RDWR))<0){
? ? ? ? perror("open file error");
? ? ? ? return -1;
? ? }?
? ? len=lseek(fd,0,SEEK_END);?
? ? ptr=mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);//读写得和open函数的标志相一致,否则会报错
? ? if(ptr==MAP_FAILED){
? ? ? ? perror("mmap error");
? ? ? ? close(fd);
? ? ? ? return -1;
? ? }?
? ? close(fd);//关闭文件也ok
? ? printf("length is %d\n",strlen(ptr));
? ? printf("the %s content is:\n%s\n",argv[1],ptr);
? ? ptr[0]='c';//修改其中的一个内容
? ? printf("the %s content is:\n%s\n",argv[1],ptr);
? ? munmap(ptr,len);//将改变的文件写入内存
? ? return 0;
}