FtpGetFiles()函数详细解释详见官方文档
https://docs.microsoft.com/en-us/windows/win32/api/wininet/nf-wininet-ftpgetfilea
网上搜这个函数发现这个函数介绍的有点少,所以将自己运行成功的代码放上来希望能够帮到一起学习的人。
InternetOpen
获取句柄,并将句柄传入函数InternetConnect
函数,这一步与链接Mysql类似,获取了Connection句柄我们就可以使用Ftp的相关函数HINTERNET hint;
HINTERNET hFtp;
hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
if (hint == NULL)
return -1;
hFtp = InternetConnect(hint, ftpSvrIp.c_str(), port, userName.c_str(), password.c_str(), INTERNET_SERVICE_FTP, 0, 0);
if (hFtp == NULL)
return -1;
InternetConnect
的方法是下面几种,因为是想要做文件自动下载更新的C++ 实现FTP上传文件博客,在这篇文章里面提供了文件上传的相关函数使用。FtpGetFile
函数中有一个参数FTP_TRANSFER_TYPE_UNKNOWN | INTERNET_FLAG_RELOAD
,后一个是为了防止文件更新后依旧从缓存中下载旧版本文件。int main()
{
char* buffer = _getcwd(NULL, 0);
//ftp地址
string ftpSvrIp = "********";
//ftp端口
int port = 21;
//用户名
string userName = "ftpUser";
//用户密码
string password = "******";
//上传文件源路径
string sourceFilePath = "E:/11.txt";
//上传文件目的路径
string desFilePath = "./11.txt";
vector<string> files;
HINTERNET hint;
HINTERNET hFtp;
hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
if (hint == NULL)
return -1;
hFtp = InternetConnect(hint, ftpSvrIp.c_str(), port, userName.c_str(), password.c_str(), INTERNET_SERVICE_FTP, 0, 0);
if (hFtp == NULL)
return -1;
HINTERNET isHas = FtpFindFirstFile(hFtp, desFilePath.c_str(), NULL, 0, 0);
if (isHas == NULL)
return -1;
// 使用此方法不会将文件替换,而是维持旧版本不变,需要删除重新下载才可以
// 如果希望下载的时候替换掉原来的文件,需要将参数参数修改为FALSE
// 原因:
// Indicates whether the function should proceed if a local file of the specified name already exists. If fFailIfExists is TRUE and the local file exists, FtpGetFile fails.
// 如果这项参数设置为TRUE,在发现有同名文件后自动停止函数运行失败。
BOOL bl = FtpGetFile(hFtp, desFilePath.c_str(), sourceFilePath.c_str(), FALSE, NULL, FTP_TRANSFER_TYPE_UNKNOWN | INTERNET_FLAG_RELOAD, 0);
InternetCloseHandle(hint);
InternetCloseHandle(hFtp);
cout << "succeed" << endl;
system("pause");
return 0;
}