linux C学习笔记04--内存映射

内存映射代码,打开一个文件与映射到内存中,对内存和文件的修改都会反映到文件中来,反之亦然,先贴代码,以后再完善:

/*************************************************************************
    > File Name: memory_map.c
    > Author: hailin.ma
    > Mail: mhl2018@126.com 
    > Created Time: Thu 28 May 2015 08:20:50 AM CST
 ************************************************************************/

#include<stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>

#define MEM_MAP_SIZE 1000

int memory_map()
{
    char * pmap = NULL;
    int fd;
    char rdbuf[100] = "\0";

    fd = open("memory.txt",O_RDWR|O_CREAT|O_TRUNC,0660);

    if(fd == -1)
    {
        perror("open error");
        return -1;
    }

    write(fd,"hello world!",MEM_MAP_SIZE);        //write data to file,the write size must as long as MEM_MAP_SIZE
    
    pmap = mmap(NULL,MEM_MAP_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);        //map memory with file

    printf("the memory is: %s\n",pmap);

    memset(pmap,'a',MEM_MAP_SIZE);
    memcpy(pmap,"this is memory map",18);        //try to chang any charactor in memory
    
    lseek(fd,0,SEEK_SET);            //move fd pointer to begin section
    
    memset(rdbuf,0,sizeof(rdbuf));
    read(fd,rdbuf,100);                //read the context in file

    printf("the file is: %s\n",rdbuf);

    munmap(pmap,10);

    close(fd);

    return 0;
}

main函数调用后运行效果图:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值