C++实现的FTP案例代码解析

2016-01-05 19:46:22|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:C/C++, 网络通信|来源:唯设编程网

20. 使用递归的方式创建本地目录

如果需要从FTP服务器下载目录,则需要创建本地对应的目录:

int CFTP::local_create_dir( const char* localPath )
{
	char tmpDIR[MAX_PATH] = {0};
	for(int i=0; i<=strlen(localPath); ++i){
		//检测中间目录是否已经存在,不存在则创建
		if(localPath[i] == '' || localPath[i] == '/' || i==strlen(localPath)){
			int iRet = access(tmpDIR,0);
			if(iRet){
				iRet = mkdir(tmpDIR);
				if(iRet){
					std::cout<<"创建目录:""<<tmpDIR<<""失败"<<std::endl;
				}
			}
		}
		//保存字符串
		if(i<strlen(localPath))
			tmpDIR[i] = localPath[i];
	}
	return 0;
}

21. 下载指定的FTP目录到本地

int CFTP::ftp_download_dir( const char* localPath,const char* remotePath,size_t buf_size)
{
	//
	char localDIR[MAX_PATH] = {0},remoteDIR[MAX_PATH] = {0};
	//得到远程目录的名字
	for(int i=0,j=0;i<strlen(remotePath);++i){
		if(remotePath[i] == '/'){
			memset(remoteDIR,0,sizeof(remoteDIR));
			j = 0;
		}else{
			remoteDIR[j++] = remotePath[i];
		}
	}
	//组装本地目录
	strcpy(localDIR,localPath);
	strcat(localDIR,"");
	strcat(localDIR,remoteDIR);
	//遍历FTP目录
	std::vector<FILE_ITEM> vecFileList;
	int resCode = -1;
	if(!(resCode = ftp_list_dir(remotePath,vecFileList))){
		for(int i=0;i<vecFileList.size();++i){
			FILE_ITEM fileItem = vecFileList[i];
			//远程文件名
			char remoteFile[MAX_PATH] = {0};
			strcpy(remoteFile,remotePath);
			strcat(remoteFile,"/");
			strcat(remoteFile,fileItem.fName.c_str());
			//判断是目录还是文件,分别处理
			if(fileItem.type == 'd' || fileItem.type == 'D'){
				//递归下载子目录
				ftp_download_dir(localDIR,remoteFile,buf_size);
			}else{
				//检测本地目录是否存在,不存在则创建本地目录				
				if(access(localDIR,0)){
					local_create_dir(localDIR);
				}
				//本地文件名
				char localFile[MAX_PATH] = {0};
				strcpy(localFile,localDIR);
				strcat(localFile,"");
				strcat(localFile,fileItem.fName.c_str());
				//下载文件
				ftp_download(localFile,remoteFile,buf_size);
			}
		}
	}else
		return resCode;
	return 0;
}
发表评论0条 】
网友评论(共?条评论)..
C++实现的FTP案例代码解析