Home Article cp命令的实现

cp命令的实现

Release time:2020-07-24 20:16:25 Author:一蓑烟雨 Reading volume:58
/*
程序名称: cp命令实现
使用方法: ./cp.c   src  dst
*/
 
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
 
int main (int argc,char *argv[])
{
if(argc!=3)
{
printf("please input src and dst ");
exit(1);
}
int fd_src = open(argv[1],O_RDONLY);
if (fd_src==-1)
{
perror("open src error!");
exit(1);
}
 
int fd_dst = open(argv[2],O_WRONLY|O_CREAT|O_EXCL,0644);//将输入的第二个参数作为文件名打开,权限为644
if ((fd_dst==-1) && (errno == EEXIST))     //文件不存在则创建
{
printf("the dst exist,still copy? ");//存在则判断是否要覆盖
char choose;
scanf("%c",&choose);
if(choose == 'y' || choose == 'Y')
{
fd_dst = open(argv[2],O_WRONLY);     //只写模式打开
}
else
{
exit(1); //不覆盖则退出
}
 
}
 
while(1)
{
char buf[1024] = {};
memset(buf,0,sizeof(buf));
int r = read(fd_src,buf,1024);  
/*
    成功:返回读到的字节数
失败:返回-1并设置errno
ps: 写常规文件时,write的返回值通常等于请求写的字节
数count, 而向终端设备或者网络写时则不一定
*/
if(r == -1)
{
perror("read error!");
exit(1);
}
else if(r == 0)  //读到末尾
{
break;
}
write(fd_dst,buf,r);
}
close(fd_src);
close(fd_dst);
 
}
支付宝打赏 微信打赏
  
I want to comment

Search

classification

Leave a message
http://blog.rjxj513.com/
User login
You have not written any reviews yet!
You have commented!
Can only praise once!
You have a collection!