Linux C++实现拷贝文件夹

78 篇文章 12 订阅

Linux C++实现拷贝文件及文件夹

源文件:copy.cpp

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

#define BUFFER_LENGTH 8192

int IsDir(std::string path)
{
	if(path.empty())
	{
		return 0;
	}
	struct stat st;
	if(0 != stat(path.c_str(),&st))
	{
		return 0;
	}
	if(S_ISDIR(st.st_mode))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}



void CopyFile(std::string sourcePath,std::string destPath)
{
	int len = 0;
	FILE *pIn = NULL;
	FILE *pOut = NULL;
	char buff[BUFFER_LENGTH] = {0};
	
	if((pIn = fopen(sourcePath.c_str(),"r"))==NULL)
	{
		printf("Open File %s Failed...\n", sourcePath.c_str());
		return 1;
	}
	if((pOut=fopen(destPath.c_str(),"w"))==NULL)
	{
		printf("Create Dest File Failed...\n");
		return 1;
	}
	
	while((len = fread(buff,sizeof(char),sizeof(buff),pIn))>0)
	{
		fwrite(buff,sizeof(char),len,pOut);
	}
	fclose(pOut);
	fclose(pIn);
}
void CopyFolder(std::string sourcePath,std::string destPath)
{
	struct dirent* filename = NULL;
	if(0 == opendir(destPath.c_str()))
	{
		if (mkdir(destPath.c_str(),0777))
		{
		    printf("Create Dir Failed...\n");
		}
		else
		{
			printf("Creaat Dir %s Successed...\n", destPath.c_str());
		}
	}
	std::string path = sourcePath;
	if(sourcePath.back() != '/')
	{
		sourcePath += "/";
	}
	if(destPath.back() != '/')
	{
		destPath += "/";
	}
	
	DIR* dp=opendir(path.c_str());
	while(filename=readdir(dp))
	{
		std::string fileSourceFath = sourcePath;
		
		std::string fileDestPath = destPath;
		
		fileSourceFath += filename->d_name;
		fileDestPath += filename->d_name;
		if(IsDir(fileSourceFath.c_str()))
		{
			if(strncmp(filename->d_name, ".", 1) && strncmp(filename->d_name, "..", 2))
			{
				CopyFolder(fileSourceFath, fileDestPath);
			}		
		}
		else
		{
			CopyFile(fileSourceFath,fileDestPath);
			printf("Copy From %s To %s Successed\n",fileSourceFath.c_str(),fileDestPath.c_str());
		}
	}	
}

int main(int argc,char *argv[])
{
	if(argv[1]==NULL||argv[2]==NULL)
	{
		printf("Please Input Source Path and Destnation Path\n");
		return 1;
	}
	std::string sourcePath=argv[1];//source path
	std::string destPath=argv[2];//destnation path
	DIR* source=opendir(sourcePath.c_str());
	DIR* destination=opendir(destPath.c_str());
	if(!source)
	{
		printf("Source Dir Path Is Not Existed\n");
		return 1;
	}
	if(!destination)
	{
		printf("Destnation Dir Path Is Not Existed\n");
	}
	CopyFolder(sourcePath,destPath);
	
	closedir(source);
	closedir(destination);
	return 0;
}

编译指令

g++ -g copy.cpp -o copy -std=c++11

#bash中测试copy进程

./copy "/home/shared/pwz/prime" "/home/shared/pwz/wisdom"

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值