用wininet实现ftp协议

  • 时间:
  • 来源:互联网
  • 文章标签:

#include <Windows.h>
#include <Wininet.h>
#include <stdio.h>
#pragma comment(lib, "WinInet.lib")
int main()
{
     // 建立会话
    HINTERNET hInternet;
    hInternet = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if(hInternet == NULL) return false;
    // 建立连接
    HINTERNET hConnect;
    hConnect = InternetConnect(hInternet, "127.0.0.1", INTERNET_INVALID_PORT_NUMBER,
       "test", "test", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    if(hInternet == NULL) { InternetCloseHandle(hInternet); return false; }
    HINTERNET hFtpFile;
    hFtpFile = FtpOpenFile(hConnect, "phpinfo.php", GENERIC_READ, FTP_TRANSFER_TYPE_BINARY|INTERNET_FLAG_RELOAD, NULL);
    if(hFtpFile == NULL) {   InternetCloseHandle(hConnect); InternetCloseHandle(hInternet); return false; }
    char buf[1024];
    DWORD buf_len = 1024;
    DWORD buf_read = 1024;
    FILE *fp = fopen("d:\\test.php", "wb");//test.php不存在的话就自动创建
    while(1)
    {    
InternetReadFile(hFtpFile, buf, buf_len, &buf_read);
       if(buf_read == 0) break;
       fwrite(buf, 1, buf_read, fp);
    }
    fclose(fp);
    InternetCloseHandle(hFtpFile);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternet);
    return true;
}

本文链接http://www.taodudu.cc/news/show-647674.html