Chinaunix首页 | 论坛 | 博客
  • 博客访问: 245411
  • 博文数量: 35
  • 博客积分: 198
  • 博客等级: 入伍新兵
  • 技术积分: 443
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-28 10:30
文章分类

全部博文(35)

文章存档

2015年(5)

2014年(14)

2013年(8)

2012年(7)

2011年(1)

我的朋友

分类: C/C++

2013-04-18 18:02:04

mmap 函数可以将文件的内容映射成内存,并且返回内存的指针,当对这块内存进行读写,就相当于对文件进行读写,并且不需要使用write,read函数读取文件的内容,用msync 函数将内容刷进文件里面,或者也可以调用 munmap函数,调用munmap函数,会自动将内存的内容刷到文件里面,用mmap 进行映射的内存大小不能超过文件的大小,否则在调用的时候会coredown,下面就写个小例子演示,不用read ,如何将文件的内容映射到内存里。


  1. #include <sys/mman.h>
  2. #include<stdio.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #define NAME_LEN 25
  8. #define PERSON_CNT 5
  9. #define RECORD_FILE_NAME "./people.data"
  10. struct person
  11. {
  12.     int id ;
  13.     int age ;
  14.     char *name;
  15. };

  16. int write_person_info_to_file(person people[], size_t size )
  17. {
  18.     int fd = open(RECORD_FILE_NAME,O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR| S_IRWXG);
  19.     if(fd < 0)
  20.     {
  21.         return -1;    
  22.     }
  23.     for(int i = 0 ; i<size ; ++i)
  24.     {
  25.         write(fd, (void*)&people[i], sizeof(people));
  26.     }
  27.     close(fd);
  28.     return 0 ;
  29. }
  30. int main(int argc, char** argv)
  31. {
  32.     struct person people[PERSON_CNT]=
  33.     {
  34.         {10010,18,"LiLei"},
  35.         {10011,20,"HanMM"},
  36.         {10032,19,"WangJun"},
  37.         {10031,19,"CaoMeng"},
  38.         {10013,16,"XuXin"}
  39.     };
  40.     if(write_person_info_to_file(people,PERSON_CNT))
  41.     {    
  42.         //error
  43.         fprintf(stdout,"save person infomation error \n");
  44.         return 1;    
  45.     }
  46.     
  47.     int fd = open(RECORD_FILE_NAME,O_RDWR|O_APPEND,S_IRUSR|S_IWUSR| S_IRWXG);
  48.     if(fd <0 )
  49.     {
  50.         fprintf(stdout,"open person infomation error \n");
  51.         return 1;    
  52.     }
  53.     struct person *pperson = (struct person*)mmap(NULL,sizeof(person)*PERSON_CNT,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  54.     if(pperson == MAP_FAILED)
  55.     {
  56.         //error accur
  57.         fprintf(stdout,"mmap function call error \n");
  58.         close(fd);
  59.         return 1 ;    
  60.     }
  61.     close(fd);
  62.     struct person *blp = pperson;
  63.     for(int i= 0 ; i<PERSON_CNT ; ++i)
  64.     {
  65.         //由于在保存的时候,将char*指针的值保存进文件,并不是保存指针的内容,因此在映射后,blp[i].name 的值是一个无效的指针,
  66.         //要访问该指针的值的时候就会引发coredown,此处只打印name的值
  67.         printf("id=[%d], name=[%p], age=[%d]\n",blp[i].id,&blp[i].name,blp[i].age);    
  68.         
  69.     }
  70.     munmap(pperson, sizeof(person)*PERSON_CNT);
  71.     
  72.     return 0 ;
  73. }

阅读(2108) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~