mmapExample.c--内存映射实现文件的复制

来源:互联网 发布:mac 获取当前用户名 编辑:程序博客网 时间:2024/06/15 20:49
/*
 *Author:
 *Function: 使用内存映射的方法实现文件复制
 */


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


//定义文件的权限
///参照/usr/inlcude/sys/stat.h下的宏定义
#define F_Mode (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)


int main(int argc,char *argv[])
{

int file_src; //源文件的filedes
int file_dst; //目标文件的filedes
struct stat file_stat;//描述文件状态的结构体
int f_stat_ret;//fstat函数的返回值
void * src = NULL;
void * dst = NULL;
off_t retlseek;
ssize_t retwrite;


if( 3 != argc)
{
printf("Usage:./test <源文件> <目标文件>\n");
exit(-1);
}


//将源文件以只读的形式打开
file_src = open(argv[1],O_RDONLY);
if(file_src < 0)
{
perror("Open the src file:");
exit(-1);
}

//打开目标文件,指定打开的文件的操作方式为可读可写
//F_Mode指定了新的文件的访问权限
file_dst = open(argv[2],O_RDWR | O_CREAT | O_TRUNC,F_Mode);
if(file_dst < 0)
{
perror("Open the dst file:");
exit(-1);
}

//我们需要知道文件的长度,下面用struct stat结构体,具体可以在/usr/include/bits/stat.h中找到定义
//使用fstat函数获得文件的信息,保存在struct stat结构体中
f_stat_ret = fstat(file_src,&file_stat);
if(f_stat_ret < 0)
{
perror("Get the src file stat:");
exit(-1);
}

//下面将进行映射
//mmap函数的原型是:void *mmap(void *addr, size_t length, int prot, int flags,int fd, off_t offset);
//addr参数设为0,表示由系统选择
if((src = mmap(0,file_stat.st_size,PROT_READ,MAP_SHARED,file_src,0)) == MAP_FAILED)
{
perror("file src mmap:");
exit(-1);


}


#if 1
//使用lseek函数设置目标文件长度
retlseek = lseek(file_dst, file_stat.st_size-1, SEEK_SET);// 设置文件偏移量(下一次读/写的位置)
if (retlseek == (off_t)-1)
{
perror("lseek");
exit(-1);
}


retwrite = write(file_dst, "", 1);
if (-1 == retwrite)
{
perror("write");
exit(-1);
}

#endif
//下面对目标文件进行映射
// 对目标文件进行映射
if((dst = mmap(0, file_stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_dst, 0)) == MAP_FAILED)
{
printf("dst file mmap:");
exit(-1);
}


//进行内存拷贝,相当与对原文件进行相同的操作
memcpy(dst, src, file_stat.st_size);

return 0;
}
原创粉丝点击