您的位置:首页 > 运维架构 > Linux

肥猫学习日记-------------实现Linux cp命令

2019-08-08 20:33 211 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_44965638/article/details/98884682

在Linux中,cp命令为拷贝文件内容至另一个
下面为利用main参数实现的cp命令

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main(int argc,char* argv[])
{
// 检查参数是否正确
if(3 != argc)
{
printf("User:cp src dest\n");
return 0;
}

// 打开源文件
int src_fd = open(argv[1],O_RDONLY);
if(0 > src_fd)
{
perror("open");
return -1;
}

// 检查目标文件是否存在
int dest_fd = open(argv[2],O_WRONLY|O_CREAT|O_EXCL,0644);
if(0 > dest_fd)
{
printf("目标文件已经存在,是否覆盖Y/N?");
char cmd = getchar();
if('y' == cmd || 'Y' == cmd)
{
dest_fd = open(argv[2],O_WRONLY|O_TRUNC);
if(0 > dest_fd)
{
perror("open");
return -1;
}
}
else
{
return 0;
}
}

int buf[1024] = {} , ret = 0;
while(ret = read(src_fd,buf,sizeof(buf)))
{
write(dest_fd,buf,ret);
}

close(src_fd);
close(dest_fd);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: