利用ftp功能通过脚本的形式进行批量处理,代码示范如下:
1、Windows环境
// ftp命令形式实现
string commandFilePath = strShScriptFile + ".tmp";
FILE *file = fopen(commandFilePath.c_str(), "w");
if (file)
{
fprintf(file, "open %s %s\n"
"USER %s\n"
"%s\n"
"cd %s\n"
"binary\n"
"prompt n\n"
"mput %s\n"
"quit\n"
,FTPServer, FTPPort, FTPUsername, FTPPassword, uploadDirectory, "*.txt");
fclose(file);
// FTP*的参数名表示远程FTP主机的相关参数;
// 其中uploadDirectory表示目的目录;
// "*.txt"表示批量上传本地txt文件,当然可以指定具体目录上传指定文件
ShScript = strShScriptFile + ".bat";
file = fopen(ShScript.c_str(), "w");
if (file)
{
fprintf(file, "ftp.exe -n -s:%s\n"
"del %s\n"
, commandFilePath.c_str()
,"*.txt");
fclose(file);
// 调用ftp.exe,执行批量脚本,然后删除txt文件
// 通过ShellExecuteA函数执行脚本
ShellExecuteA(NULL, "open", batFilePath.c_str(), NULL, NULL, SW_HIDE);
}
else
{
printf("[Error] create shell script .bat: %s failed!\n", ShScript.c_str());
return false;
}
}
else
{
printf("[Error] create shell script .tmp: %s failed!\n", commandFilePath.c_str());
return false;
}
由于普通ftp命令在大批量传输时性能较低,可以借助ncftp实现批量传输,ncftp是对ftp进行封装,提升了处理效率,可到官网进行下载安装:
ShScript = strShScriptFile + ".bat";
FILE *file = fopen(ShScript.c_str(), "w");
if (file)
{
// 参数说明见第一部分
fprintf(file, "ncftpput.exe -u %s -p %s -P %s %s %s %s\n"
"del %s\n"
, FTPUsername, FTPPassword, FTPPort, FTPServer,uploadDirectory, "*.txt"
,"*.txt");
fclose(file);
ShellExecuteA(NULL, "open", batFilePath.c_str(), NULL, NULL, SW_HIDE);
}
else
{
printf("[Error] create shell script .bat: %s failed!\n", ShScript.c_str());
return false;
}
2、Linux环境
此处直接使用高效率的ncftp,需要到官网自行下载安装,当然也可以使用普通的ftp,参照如下格式,也可实现。
ShScript = strShScriptFile + ".sh";
FILE *file = fopen(ShScript.c_str(), "w");
if (file)
{
// 参数说明详见第一部分
fprintf(file, "#!/bin/bash\n"
"ncftpput "
"-u %s "
"-p %s "
"-P %s %s %s %s >/dev/null 2&>/dev/null\n"
// 此命令>/dev/null 2&>/dev/null, 可以避免shell回显信息
"ncftp "
"-u %s "
"-p %s "
"-P %s %s << ! >/dev/null\n"
"cd %s\n"
"lrm -f %s\n"
"quit\n"
"!\n"
"exit"
// 前后加!的作用类似C中的{},此处的作用是禁止交互和表面shell回显信息
, FTPUsername, FTPPassword, FTPPort, FTPServer, uploadDirectory, "*.txt"
// ncftp
, FTPUsername, FTPPassword, FTPPort, FTPServer, uploadDirectory
, "*.txt");
fclose(file);
chmod(ShScript.c_str(), 0755);
ShScript += "&";
// 通过system函数执行脚本
system(ShScript.c_str());
}
else
{
printf("[Error] create shell script .bat: %s failed!\n", ShScript.c_str());
return false;
}
读后有收获可以支付宝请作者喝咖啡: