// 、、使用内存映射可以拷贝文件
/*
对原始文件进行内存映射
创建一个新文件
把新文件的数据拷贝映射到内存中
通过内存拷贝将第一个文件的内存映射区拷贝到第二个文件的内存映射区
释放资源
*/
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd = open("englsih.txt", O_RDONLY);
// 获取原始文件的大小
int len = lseek(fd, 0, SEEK_END);
// 创建一个新文件,并对其大小进行拓展
int fd1 = open("cpy.txt", O_CREAT | O_RDWR, 0664);
truncate("cpy.txt", len);
write(fd1, " ", 1);
// 分别进行内存映射
void *ptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
void *ptr1 = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd1, 0);
if (ptr == MAP_FAILED)
{
perror("mmap");
exit(0);
}
if (ptr1 == MAP_FAILED)
{
perror("mmap");
exit(0);
}
// 内存拷贝
memcpy(ptr1, ptr, len);
munmap(ptr1, len);
munmap(ptr, len);
close(fd1);
close(fd);
return 0;
}
运行结果:
源文件和目标文件完全一致