使用wininet的InternetReadFile下载文件

简单地说,wininet是微软提供的用来制作网络客户端程序的类库,它封装了winsock,为开发人员提供易用的开发接口。

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

 

#include

#include

#include

#include 

#include

#include

#include

#include

 

#pragma comment(lib,"wininet")

 

using namespace std;

 

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

 

int main(int argc, char* argv[])
{
 std::cout<  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 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;
}

 

你可能感兴趣的:(c++)