1. 程式人生 > >C++下載指定Url網路地址上的檔案-Windows Api

C++下載指定Url網路地址上的檔案-Windows Api

#include <stdio.h> 
#include <Windows.h>
#include <wininet.h> 
#pragma comment (lib,"User32.lib")
#pragma comment( lib,"Urlmon.lib")
#pragma comment( lib, "wininet.lib") 
#define MAXBLOCKSIZE 1024

/**-----download(const char *Url,const char *save_as)--------------------
函式功能:將指定的Url地址的檔案下載到本地
函式引數:
		Url:檔案所指向的網路地址
		save_as:檔案儲存到本地的路徑地址
-------------------------------------------------------------------------**/
void download(const char *Url,const char *save_as)/*將Url指向的地址的檔案下載到save_as指向的本地檔案*/  
{  
	byte Temp[MAXBLOCKSIZE];  
	ULONG Number = 1;  

	FILE *stream;  
	HINTERNET hSession = InternetOpen("RookIE/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);  
	if (hSession != NULL)  
	{  
		HINTERNET handle2 = InternetOpenUrl(hSession, Url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);  
		if (handle2 != NULL)  
		{  


			if( (stream = fopen( save_as, "wb" )) != NULL )  
			{  
				while (Number > 0)  
				{  
					InternetReadFile(handle2, Temp, MAXBLOCKSIZE - 1, &Number);  

					fwrite(Temp, sizeof (char), Number , stream);  
				}  
				fclose( stream );  
			}  

			InternetCloseHandle(handle2);  
			handle2 = NULL;  
		}  
		InternetCloseHandle(hSession);  
		hSession = NULL;  
	}  
} 
int WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
	/*****第1種、使用自帶的WindowsAPI-URLDownloadToFile()函式下載檔案******/
	/*char *url = "http://imgsrc.baidu.com/forum/pic/item/596da61ea8d3fd1f750432d8304e251f94ca5f2d.jpg";
	HRESULT hr = URLDownloadToFile(0,url,"mypic.jpg",0,NULL);
	*/
	/*****第2種、使用download()函式下載檔案******/
	MessageBox(NULL,"正在下載","下載",MB_OK);
	download("http://imgsrc.baidu.com/forum/pic/item/596da61ea8d3fd1f750432d8304e251f94ca5f2d.jpg","mypic.jpg");
	MessageBox(NULL,"下載完成","下載",MB_OK);
	return 0;
}