使用C ++下载HTML页面

时间:2014-10-10 11:18:26

标签: c++ winapi wininet

这是我的代码。我已将wininet.lib附加到其他依赖项。

#include <iostream>
#include <Windows.h>
#include <WinInet.h>

using namespace std;

int main()
{
    HINTERNET hSession, hURL;
    char* Buffer = new char[1024];
    DWORD BufferLen, BytesWritten;
    HANDLE FileHandle;

    hSession = InternetOpen(NULL, 0, NULL, NULL, 0);
    hURL = InternetOpenUrl(hSession, "http://www.google.co.uk", NULL, 0, 0, 0);

    FileHandle = CreateFile("C:\temp.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
    if (FileHandle == NULL) { cout << "FileHandle == NULL" << endl; }
    BytesWritten = 0;
    do
    {
        InternetReadFile(hURL, Buffer, 1024, &BufferLen);
        WriteFile(FileHandle, Buffer, BufferLen, &BytesWritten, NULL);
    } while (BufferLen != 0);
    CloseHandle(FileHandle);

    InternetCloseHandle(hURL);
    InternetCloseHandle(hSession);

    ShellExecute(0, "open", "C:\\temp.txt", NULL, NULL, 1);

    cout << "Operation complete!" << endl;
    system("PAUSE");
    return 0;
}

即使句柄非空,也不会创建我的输出文件C:\ temp.txt。我想知道为什么会这样,如果我的其余代码是正确的。谢谢。

0 个答案:

没有答案