linux - CP命令

CP命令的代码实现

实现思维:
1、 传参到程序内
2、 判断传入参数数量
3、 打开源文件
4、 计算文件大小
5、 开辟缓存空间
6、 初始化缓存空间
7、 读取打开的源文家内容到缓存空间
8、 关闭打开的源文件
9、 创建目标文件,并判断文件是否存在

  • 如果目标文件存在,则给于判断选项,是否继续copy
  • 如果继续则清除目标文件内容
  • 写入缓存区内容到目标文件

10、 把缓存空间的内容写入到打开的目标文件

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

int copy(char **argv)
{
	int fdDes;
	printf("%s exist!\nContinue to copy %s file, overwrite %s file content!\nyes or no Copied to the %s file锛焅ny/n\n",argv[2],argv[1],argv[2],argv[2]);
	char *a = (char *)malloc(sizeof(char)*2);
	memset(a,0,sizeof(a));
	char *b = "y";
	char *c = "n";
	scanf("%c",a);
	if(strcmp(a,b) == 0){
		fdDes = open(argv[2],O_RDWR|O_TRUNC);
	}else if(strcmp(a,c) == 0){
		printf("over!");
		exit(0);
	}
	else{
		printf("Input error!\nPlease copy again %s file",argv[2]);
		exit(0);
	}
	return fdDes;
}

int main(int argc, char **argv)
{
	if(argc != 3){
		printf("params error");
		exit(-1);
	}
	
	int fdDes;
	fdDes = open(argv[2],O_RDWR|O_CREAT|O_EXCL,0600);
	if(fdDes == -1){
		fdDes = copy(argv);
	}
	int fdSrc;
	fdSrc = open(argv[1],O_RDWR);
	if(fdSrc == -1){
		printf("Not this is file");
		exit(-1);
	}
	int size = lseek(fdSrc, 0, SEEK_END);
	lseek(fdSrc, 0, SEEK_SET);
	char *readBuf = NULL;
	readBuf = (char *)malloc(sizeof(char)*size + 8);
	memset(readBuf, 0, size + 8);
	int n_read = read(fdSrc, readBuf,size);
	if(n_read != -1){
		printf("read %d byte to Buf\n",n_read);
	}
	close(fdSrc);
	int n_write = write(fdDes, readBuf,strlen(readBuf));
	if(n_write != -1){
		printf("succeed copy %d char write to %s\n",n_write,argv[2]);
	}
	close(fdDes);

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值