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/archive/2011/10/17/2215684.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值