在Linux下,cp拷贝的命令有如下格式:
cp main.c main1.c
cp main.c dir
文件的名字:my_cp.c
1.主函数中我们需要参数,所以应该设计成
int main(int argc,char *argv[])
{
exit(0);
}
其中:
argv[0] : “./my_cp.c”
argv[1] : “源文件的路径+文件名”
argv[2] : “目的文件的路径/文件名”
argc : 参念列表中的参数个数
思路:
1.判断参数列表中的个数是否够,不够的话是没有办法进行拷贝的,肯定是缺少元素的。
2.以只读的方式 打开源文件
3.在打开目的文件之前我们需要判断是普通文件还是目录文件,使用方法stat。因为处理方法是不一样的。
4.打开目标文件,方式是只写、创建、和清空:如果文件存在就清空,没有就创建。
5.循环写入。
6.关闭文件。
#include <stdio.h>
//#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
//1
if(argc < 3)
{
printf("mycp error:Parameter is not enough!\n");
exit(0);
}
//2
int fr = open(fr,O_RDONLY);
if(-1 == fr)
{
perror("open1 error:");
exit(0);
}
//3
struct stat st;
int n = stat(argv[2],&st);
char path[128] = {0};
//无论是普通文件还是目录文件都需要做这一步
strcpy(path,argv[2]);
//是目录文件
if(S_ISDIR(st.st_mode) && n != -1)
{
char *p = argv[1] + strlen(argv[1]);
while(*p != '/' && p != argv[1])
{
p--;
}
strcat(path,"/");
strcat(path,p);
}
//4
int fw = open(path,O_WRONLY | O_CREAT | O_TRUNC,0664);
if(-1 == fw)
{
perror("open2 error:");
exit(0);
}
//5
printf("start copy:\n");
while(1)
{
char buffer[128] = {0};
int num1 = read(fr,buffer,127);
if(-1 == num1)
{
break;
}
int num2 = write(fw,buffer,num1);
if(-1 == num2)
{
break;
}
}
//6
close(fr);
close(fw);
exit(0);
}