2015-01-17 20:00:57|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 网络通信|来源:唯设编程网
//递归创建本地目录
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;
}
这个函数实现递归方式创建本地目录,使用到的核心函数是mkdir。首先通过access判断本地目录是否存在。
//下载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;
}
这个函数用来下载FTP目录。首先调用ftp_list_dir列出服务器目录的文件和子目录,再递归下载子目录中的内容到本地。