Linux下mmap函数的一个练习

mmap函数用来将文件映射进内存。需要指出的是这里的内存指的是虚拟内存。

mmap函数可以将一个文件的内容映射到内存,这样就可以直接对该内存进行操作,从而省去IO操作。

下面是一个小例子:

 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #include<error.h>
5 #include<fcntl.h>
6 #include<sys/mman.h>
7 #include<unistd.h>
8 int main(int argc,char *argv[]){
9 int fd,len;
10 char *ptr;
11 if(argc<2){
12 printf("please enter a file\n");
13 return 0;
14 }
15 if((fd=open(argv[1],O_RDWR))<0){
16 perror("open file error");
17 return -1;
18 }
19 len=lseek(fd,0,SEEK_END);
20 ptr=mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);//读写得和open函数的标志相一致,否则会报错
21 if(ptr==MAP_FAILED){
22 perror("mmap error");
23 close(fd);
24 return -1;
25 }
26 close(fd);//关闭文件也ok
27 printf("length is %d\n",strlen(ptr));
28 printf("the %s content is:\n%s\n",argv[1],ptr);
29 ptr[0]='c';//修改其中的一个内容
30 printf("the %s content is:\n%s\n",argv[1],ptr);
31 munmap(ptr,len);//将改变的文件写入内存
32 return 0;
33 }

关于虚拟内存的概念可以查看http://zh.wikipedia.org/wiki/%E8%99%9A%E6%8B%9F%E5%86%85%E5%AD%98,里面有简单的介绍

原文地址:https://www.cnblogs.com/aLittleBitCool/p/2215684.html