文件I/O-文件内存映射


定义

参数



注意事项


文件与内存映射


// 修改文件内存映射
#include 
#include    // mmap
#include    // open
#include   // open
#include       // open
#include      // lseek,write
#include      // memcpy


int main(int argc, char *argv[]) {
    int fd;
    char *mapped_mem, *p;
    int flength = 1024;
    //void * start_addr = 0;

    fd = open(argv[1], O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR);
    flength = lseek(fd, 1, SEEK_END);
    write(fd, "\0", 1);
    lseek(fd, 0, SEEK_SET);
    mapped_mem = (char *)mmap(  NULL,                   // 系统自己决定映射区起始地址 
                                flength,                // 映射区数据长度
                                PROT_READ,              // 映射区保护方式
                                MAP_PRIVATE,            // 共享方式
                                fd,
                                0);
    /*使用映射区域*/
    printf("%s\n", mapped_mem);
    close(fd);
    munmap(mapped_mem, flength);       // 删除内存映射
    return 0;
}

修改文件的内存映像

#include 
#include    // mmap
#include    // open
#include   // open
#include       // open
#include      // lseek,write
#include      // memcpy


int main(int argc, char *argv[]) {
    int fd;
    char *mapped_mem, *p;
    int flength = 1024;

    fd = open(argv[1], O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR);
    flength = lseek(fd, 1, SEEK_END);
    write(fd, "\0", 1);
    lseek(fd, 0, SEEK_SET);
    mapped_mem = (char *)mmap(  NULL,                   // 系统自己决定映射区起始地址 
                                flength,                // 映射区数据长度
                                PROT_READ | PROT_WRITE, // 映射区保护方式
                                MAP_SHARED,             // 共享方式
                                fd,
                                0);
    /*使用映射区域*/
    printf("%s\n", mapped_mem);

    while ((p = strstr(mapped_mem, "ass"))) {
        memcpy(p, "123", 3);
        p += 3;
    }
    close(fd);
    munmap(mapped_mem, flength);       // 删除内存映射
    return 0;
}