#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);mmap,存储映射,将文件映射到内存地址(指针),然后可以利用指针操作函数(如memcpy等)进行操作
例如用mmap复制文件:
//目的:利用mmap将fd1文件复制到fd2文件
//1-打开文件 //2-获取文件大小 //3-开辟fd2文件大小(在fd2文件的末尾写一个空字节) //4-mmap映射fd1文件 //5-mmap映射fd2文件 //6-关掉fd1, fd2 //7-用memcpy将fd1拷贝到fd2中 //9-munmap//代码如下:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 11 int main(void)12 { 13 int fd1 = open("1.txt", O_RDONLY);14 int fd2 = open("2.txt", O_RDWR|O_CREAT, ~0);15 16 struct stat fd_st;17 fstat(fd1, &fd_st);18 19 printf("size=%d\n", fd_st.st_size);20 21 lseek(fd2, fd_st.st_size-1, 0);22 write(fd2, "", 1);23 void *src = mmap(NULL, fd_st.st_size, PROT_READ, MAP_SHARED, fd1, 0);24 void *dst = mmap(NULL, fd_st.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd2, 0);25 26 if (src==MAP_FAILED || dst==MAP_FAILED)27 printf("errmsg=%s\n", strerror(errno));28 29 close(fd1);30 31 close(fd2);32 33 memcpy(dst, src, fd_st.st_size);34 35 //msync(dst, fd_st.st_size, MS_SYNC);36 37 munmap(src, fd_st.st_size);38 munmap(dst, fd_st.st_size);39 40 return 0;41 }