c++编程 实现下载文件

 1 下载文件要用到操作系统的API函数,下面是一个WINDOWS系统中的实现:
2
3 //---------------------------------------------------------------------------
4
5 #include <stdio.h>
6 #include <windows.h>
7 #include <wininet.h>
8 #define MAXBLOCKSIZE 1024
9 #pragma comment( lib, "wininet.lib" ) ;
10
11 void download(const char *Url,const char *save_as)/*将Url指向的地址的文件下载到save_as指向的本地文件*/
12 {
13 byte Temp[MAXBLOCKSIZE];
14 ULONG Number = 1;
15
16 FILE *stream;
17 HINTERNET hSession = InternetOpen((LPCWSTR)"RookIE/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
18 if (hSession != NULL)
19 {
20 HINTERNET handle2 = InternetOpenUrl(hSession, (LPCWSTR)Url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
21 if (handle2 != NULL)
22 {
23
24
25 if( (stream = fopen( save_as, "wb" )) != NULL )
26 {
27 while (Number > 0)
28 {
29 InternetReadFile(handle2, Temp, MAXBLOCKSIZE - 1, &Number);
30
31 fwrite(Temp, sizeof (char), Number , stream);
32 }
33 fclose( stream );
34 }
35
36 InternetCloseHandle(handle2);
37 handle2 = NULL;
38 }
39 InternetCloseHandle(hSession);
40 hSession = NULL;
41 }
42 }
43
44 int main(int argc, char* argv[]){
45
46 download("http://www.baidu.com/","c:\\index.html");/*调用示例,下载百度的首页到c:\index.html文件*/
47 return 0;
48 }

以上,转自:http://zhidao.baidu.com/question/126310723.html


 

posted @ 2011-11-20 14:26  贰百舞  阅读(6202)  评论(1编辑  收藏  举报