您的位置:首页 > 运维架构 > Linux

linux c 通过内存映射,操作文件

2016-10-31 20:12 381 查看
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/mman.h>

/*

 MAP_SHARED: 映射区的数据直接反映到文件中

       

 MAP_PRIVATE:映射区的数据不会反映到文件中

*/

struct msg

{

 char name[20];

 int age;

};

int main()

{

  int fd = open("obj",O_RDWR|O_CREAT,0664);

  if(fd == -1) perror("open"),exit(-1);

 

  int ret = ftruncate(fd,sizeof(struct msg)*20);

  if(ret == -1) perror("ftruncate"),exit(-1);

 

  void* pp = mmap(NULL,sizeof(struct msg),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

  struct msg* p =pp;

  for(int i = 0;i<20;i++)

  {

   strcpy(p->name,"袁苏东!\n");

   p->age= 10;

   p++;

  }

  munmap(pp,sizeof(struct msg)*20);

  close(fd);

  return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐