#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>
#define BUF_NUM 128
/*函数功能:文件复制,参数:源文件和目标文件的文件描述符*/
int mycp(int src,int dest)
{
char buf[BUF_NUM]; /*声明一字符数组,用来存储从源文件中读取的数据*/
int r_ret,w_ret; /*声明实际读 写的大小*/
char *p;
bzero(buf,BUF_NUM);/*初始化数组*/
if(src<0 || dest<0){
printf("open file error\n");
return 1;
}
while((r_ret=read(src,buf,BUF_NUM))>0){ /*读取,存储*/
p=buf;
while(r_ret){ /*将读出的数据全部写入目标文件*/
w_ret=write(dest,p,r_ret);
r_ret=r_ret-w_ret;
p=p+w_ret;
}
bzero(buf,BUF_NUM);
}
return 0;
}
/*主函数*/
int main(int argc,char *argv[])
{
if(argc!=3){
printf("command is error\n");
return 1;
}
int src,dest,ret;
src=open(argv[1],O_RDONLY); /*只读方式打开源文件*/
dest=open(argv[2],O_WRONLY|O_TRUNC|O_CREAT,0666);/*只写方式打开目标文件,如果文件不存在,先创建*/
if((ret=mycp(src,dest))!=0){ /*调用函数,复制文件*/
printf("copy file failed\n");
return 1;
}
else
printf("copy file is successful\n");
close(src);
close(dest);
return 0;
}