http文件下载

很多时候要从http服务器上下载文件, C++相关的web库也很多, 比如winiet, winhttp, xmlhttp,curl等等

最简单的就是wininet:

#include <Windows.h>
#include <WinInet.h>
#pragma comment(lib, "wininet.lib")

#define URL L"http://dlsw.br.baidu.com/ditui/Baidu_Setup_1.8.200.924_ftn.exe"
int _tmain(int argc, _TCHAR* argv[])
{
	HINTERNET  hInternet;
	HINTERNET  hFile;

	DWORD  dwStatusCode;
	TCHAR  dwLenth[32] = {0};
	DWORD  dwSize = sizeof(DWORD);

	int  nfilesize;                     

	hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);


	if(hInternet == NULL)
	{
		return false;
	}

	hFile = InternetOpenUrl(hInternet, URL, NULL, 0, INTERNET_FLAG_RESYNCHRONIZE,NULL);
	if(hFile == NULL)
	{
		InternetCloseHandle(hInternet) ;
		return false;
	}

	BOOL bRet = HttpQueryInfo(hFile, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwSize,NULL);
	if(200 != dwStatusCode) 
	{
		InternetCloseHandle(hInternet) ;
		InternetCloseHandle(hFile) ;
		return false;
	}
	if(HttpQueryInfo(hFile,HTTP_QUERY_CONTENT_LENGTH, &dwLenth,&dwSize1,NULL))
	{
		nfilesize = _ttoi(dwLenth);                // file size.
	}

	HANDLE hDownFile = CreateFile(L"D:\\browser.exe",
		GENERIC_READ|GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL);

	if(INVALID_HANDLE_VALUE == hDownFile)
	{
		InternetCloseHandle(hInternet) ;
		InternetCloseHandle(hFile) ;

		return false;
	}

	DWORD dwWrite, dwBytesRead = 0;
	char  bufFile[16*1024] = {0};    

	while(true)
	{
		BOOL bRead = InternetReadFile(hFile, bufFile, sizeof(bufFile), &dwBytesRead);
		if(dwBytesRead == 0)                // End of file.
			break;
		WriteFile(hDownFile, bufFile, dwBytesRead, &dwWrite,NULL);
	}

	InternetCloseHandle(hFile) ;
	InternetCloseHandle(hInternet) ;
	CloseHandle(hDownFile) ;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值