Chinaunix首页 | 论坛 | 博客
  • 博客访问: 113393
  • 博文数量: 29
  • 博客积分: 826
  • 博客等级: 上士
  • 技术积分: 390
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-11 08:30
文章分类
文章存档

2012年(29)

我的朋友

分类: LINUX

2012-06-24 20:59:17

映射只读文件,运行是要加参数,例如:编译 gcc mmap.c -o mmap 执行 ./mmap 1.txt
 
#include
#include
#include
#include
#include
#include

int main(int argc, char **argv)
{
 int fd;
 char *mapped_mem,*p;
 int flength =1024;
 void* start_addr=0;
 
 fd=open(argv[1],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
 flength=lseek(fd,1,SEEK_END);
 write(fd,"\0",1);
 lseek(fd,0,SEEK_SET);
 mapped_mem=mmap(start_addr,flength,PROT_READ,MAP_PRIVATE,fd,0);
 printf("%s\n",mapped_mem);
 close(fd);
 munmap(mapped_mem,flength);
 return 0;
}
 
 
可读可写
#include
#include
#include
#include
#include
#include
#include
 
int main(int argc, char **argv)
{
 int fd;
 char *mapped_mem, * p;
 int flength = 1024;
 void *start_addr=0;
 
 fd =open(argv[1],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
 flength =lseek(fd,1,SEEK_END);
 write(fd,"\0",1);
 lseek(fd, 0, SEEK_SET);
 //start_addr=0x80000;
 mapped_mem = mmap(start_addr,flength,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
 printf("%s\n",mapped_mem);
 while((p=strstr(mapped_mem,"Hello")))
 {
  memcpy(p,"Linux",5);
  p+=5;
 }
 mapped_mem[1]='x';            //mapped_mem就是个字符串
 printf("\n\n%s\n",mapped_mem);
 close(fd);
 munmap(mapped_mem, flength);
 return 0;
}
阅读(1803) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~