010 下載網頁

Post date: 2012/7/3 上午 11:22:54

#include <windows.h> #include <iostream> #include <fstream> #include <cstdlib> #include <wininet.h> #pragma comment(lib,"wininet")//連結lib using namespace std; const int BUF_SIZE = 1024; int Download(const string& url, ostream& output) { char buffer[BUF_SIZE]; HINTERNET hUrl, hInet; DWORD rcv, total = 0; if (InternetAttemptConnect(0) != ERROR_SUCCESS) return 0; hInet = InternetOpen("download", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (hInet == NULL) return 0; hUrl = InternetOpenUrl(hInet, url.c_str(), NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE, 0); if (hUrl == NULL) return 0; do { InternetReadFile(hUrl, &buffer, BUF_SIZE, &rcv); output.write(buffer, rcv); total += rcv; } while (rcv > 0); InternetCloseHandle(hUrl); InternetCloseHandle(hInet); return total; } int main() { ofstream f("test.txt"); int re = Download("http://social.msdn.microsoft.com/Forums/zh-HK/234/thread/0edbd850-821f-40f2-b43e-7788ac090db6", f); cout << "共收到 " << re << " byte. \n"; system("pause"); }