使用wininet的InternetReadFile下载文件

简单地说,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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值