映射只读文件,运行是要加参数,例如:编译 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;
}
阅读(1308) | 评论(0) | 转发(0) |