linux下C语言实现cp命令复制文件与文件夹

版权声明:本文为博主原创文章,未经博主允许,欢迎随意转载,标好作者+原文地址就可以了!感谢欣赏!觉得好请回个贴! 

https://blog.csdn.net/jackcsdnfghdtrjy/article/details/86551475

1、使用标准I/O实现文件复制;

2、使用目录检索寻找文件夹,并递归复制文件夹。

代码:

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

int is_dir(char* path);//判断是否是目录  是返回1 否则返回0
int copy_file(char* srcPath,char *destPath);//复制文件  成功返回0 否则返回 -1
int copy_folder(char* srcPath,char *destPath);//复制文件夹  成功返回0 否则返回 -1

int main(int argc,char *argv[])  //argv[1] 源文件  argv[2] 目标文件
{
	if(argc != 3)
	{
		printf("Usage srcfile destfile\n");
		return -1;
	}
	char* srcPath=argv[1];
	char* destPath=argv[2];

	if(is_dir(srcPath)) //文件夹的拷贝
	{
		copy_folder(srcPath,destPath);
	}
	else
	{
		if(access(destPath,F_OK) == 0)  //保证destPath是未存在的目录
		{
			printf("目标文件已存在\n");
			return -1;
		}
		copy_file(srcPath,destPath);//文件进行拷贝
	}
	return 0;
 
}
//判断是否是目录  是返回1 否则返回0
int is_dir(char* path)
{
	struct stat st;
	stat(path,&st);
	if(S_ISDIR(st.st_mode))
		return 1;
	else
		return 0;
}

//复制文件  成功返回0 否则返回 -1
int copy_file(char* srcPath,char *destPath)
{
	char Buf[1024] = {0};
	int count_read = 0;
	long fp_src_ltell = 0,fp_src_atell = 0;
	FILE* fp_src = fopen(srcPath,"r");//只读方式打开
	FILE* fp_dst = fopen(destPath,"w");//只写方式打开
	if(fp_dst ==NULL || fp_src == NULL)
	{
		printf("文件打开有问题\n");
		return -1;
	}
	while(1)
	{
		memset(Buf,0,sizeof(Buf));
		fp_src_ltell = ftell(fp_src); //上一次文件指针位置
		count_read = fread(Buf,sizeof(Buf),1,fp_src);
		fp_src_atell = ftell(fp_src); //当前文件指针位置
		if(count_read<1) //异常或到达末尾结束
		{
			if(feof(fp_src))
			{
				long temp = fp_src_atell - fp_src_ltell;
				fwrite(Buf,temp,1,fp_dst); //成功
				return 0;
			}
			else if(ferror(fp_src))
			{
				perror("fread error:");
				return -1;
			}
		}
		fwrite(Buf,sizeof(Buf),1,fp_dst);
	}
	return 0;
}

//复制文件夹
int copy_folder(char* srcPath,char *destPath)
{
	char newsrcPath[4096];
	char newdestPath[4096];
	
	if (mkdir(destPath,0777))//如果不存在就用mkdir函数来创建
	{
		printf("目标文件已存在\n");
		return -1;
	}
	
	DIR* srcDp = opendir(srcPath);
	if(srcDp == NULL)
	{
		printf("打开文件夹[%s]失败!\n",srcPath);
		return -1;
	}
	struct dirent * srcDirent = NULL;
	int flag = 0;
	while(srcDirent = readdir(srcDp))
	{
		flag++;
		if(flag>2) //去除隐藏文件 . ..
		{
			bzero(newsrcPath,sizeof(newsrcPath)); //清空
			bzero(newdestPath,sizeof(newdestPath));
				
			sprintf(newsrcPath,"%s/%s",srcPath,srcDirent->d_name);//保存新的文件路径
			sprintf(newdestPath,"%s/%s",destPath,srcDirent->d_name);
			
			if(srcDirent->d_type == DT_DIR) //文件夹的拷贝
				copy_folder(newsrcPath,newdestPath);
			else 					     	 //普通文件
				copy_file(newsrcPath,newdestPath);
		}
			
	}
	return 0;
}

运行:

复制rr文件夹,rr文件夹如下图:

运行过程与结果:

猜你喜欢

转载自blog.csdn.net/jackcsdnfghdtrjy/article/details/86551475