您的位置:首页 > 其它

使用wininet的InternetReadFile下载文件

2012-08-10 15:02 330 查看
简单地说,wininet是微软提供的用来制作网络客户端程序的类库,它封装了winsock,为开发人员提供易用的开发接口。

基本上每天我们都会从网络上上传或下载一些文件。今天就简单地使用wininet函数实现下载文件的功能。代码如下:

#include <windows.h>

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <wininet.h>

#include <shellApi.h>

#include <ShlObj.h>

#pragma comment(lib,"wininet")

using namespace std;

bool DownloadFile(LPCTSTR szUrl,LPCTSTR szLocalFile,BOOL bFailIfExists);

int main(int argc, char* argv[])

{

std::cout<<DownloadFile("http://hi.baidu.com/new/failnorth","d:\\failnorth.htm",TRUE)<<std::endl;

getchar();

return 0;

}

bool DownloadFile(LPCTSTR szUrl,LPCTSTR szLocalFile,BOOL bFailIfExists)

{

if (bFailIfExists &&

!PathIsDirectory(szLocalFile) &&

(GetFileAttributes(szLocalFile) != INVALID_FILE_ATTRIBUTES))

{

return false;

}

HANDLE hFile = INVALID_HANDLE_VALUE;

HINTERNET hInet = NULL;

HINTERNET hUrl = NULL;

DWORD dwBuf = 1024*1024,dwRead = 0; //1M

auto_ptr<char> szBuf(new char[dwBuf]);

memset(szBuf.get(),0,dwBuf);

std::string strTmp;

bool bRet = false;

try

{

hFile = CreateFile(szLocalFile,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

if (hFile == INVALID_HANDLE_VALUE)

throw "error";

hInet = InternetOpen(NULL,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);

if (hInet == NULL)

throw "error";

hUrl = InternetOpenUrl(hInet,szUrl,NULL,0,

INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD,0);

if (hUrl == NULL)

throw "error";

for(;;)

{

if (!InternetReadFile(hUrl,szBuf.get(),dwBuf,&dwRead))

{

bRet = false;

break;

}

if (dwRead == 0)

{

bRet = true;

break;

}

//strTmp += std::string(szBuf,dwRead);

WriteFile(hFile,szBuf.get(),dwRead,&dwRead,NULL);

}

throw "ok";

}

catch(...)

{

if (hFile != INVALID_HANDLE_VALUE)

CloseHandle(hFile);

if (hUrl != NULL)

InternetCloseHandle(hUrl);

if (hInet != NULL)

InternetCloseHandle(hInet);

}

return bRet;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: