mmap接口--应用

一 mmap用于映射文件的读写

#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define handle_error(msg) do{perror(msg);exit(EXIT_FAILURE);} while(0)

int main(int argc, char *argv[])
{
        int fd; 
        off_t length;
        char *addr;
        //char *inserted = "## inserted ##"; // this str will be inserted to the file
        char *inserted = "laoliang";
        //int pos = 5; // the position to insert
        int pos = 0;
        fd = open("abc.txt", O_RDWR | O_CREAT, 0644);
        if(fd == -1){
            handle_error("open file error");
        }
        length = lseek(fd, 1, SEEK_END);
        printf("length = %d\n",length);
        write(fd, "\0", 1); 
        addr = (char *)mmap(NULL, length + strlen(inserted), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); 
        //addr = (char *)mmap(NULL, length + strlen(inserted), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
        printf("addr = %p\n",addr);
        memcpy(addr + pos + strlen(inserted), addr + pos, length - pos);
        memcpy(addr + pos, inserted, strlen(inserted));
        close(fd);
        munmap((void *)addr, length);
        return 0;

}
posted @ 2022-02-09 20:50  行者行者行者  阅读(84)  评论(0)    收藏  举报