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;
}