使用mmap在內存中讀寫文件


通常情況下是使用read/write,fread/fwrite等來讀寫文件,linux提供了一種方式可以將文件映射到內存,然后可以用字符串的方式對它進行讀寫操作,並寫回到文件。 

下面是一段測試代碼,目的: 用mmap將文件abc.txt映射到內存,利用字符串函數向該內存中插入一個字符串,以達到修改文件的目的。

 

 

 #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>

#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
         int pos =  5//  the position to insert
        fd = open( " abc.txt ", O_RDWR | O_CREAT,  0644);
         if(fd == - 1)
        {
                handle_error( " open file error ");
        }
        length = lseek(fd,  1, SEEK_END);
        write(fd,  " \0 "1);
        addr = ( char *)mmap(NULL, length + strlen(inserted), PROT_READ | PROT_WRITE, MAP_SHARED, fd,  0);
        memcpy(addr + pos + strlen(inserted), addr + pos, length - pos);
        memcpy(addr + pos, inserted, strlen(inserted));
         // printf("addr: %s", addr);
        close(fd);
        munmap(( void *)addr, length);
}

 

運行:

zhangxd@ubuntu:~/linux$ cat abc.txt 
This is the first message.
zhangxd@ubuntu:~/linux$ ./test 
zhangxd@ubuntu:~/linux$ cat abc.txt 

This ## inserted ##is the fir 

 

可以看到文件內容已經被修改了,細心的朋友會發現,mmap時申請的長度大於文件的長度,但是最終文件的長度並沒有改變,由此得出結論:mmap是不能修改文件的長度的。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM