How do I save a webpage using C++? Windows or Linux System

社会主义新天地 提交于 2019-12-02 17:53:06

问题


I need to know how to save a webpage using C++ on a Windows and/or Linux.

Step 1) This is my current code that opens the webpage:

ShellExecute(NULL, "open", websiteURL, NULL, NULL, SW_SHOWNORMAL);

Step 2) This is the step where I will save the webpage that is opened as a .txt

Your help here.

Step 3) This is my attempt at closing the webpage after saving it as a .txt; However, it does not work currently.

ShellExecute(NULL, "close", websiteURL, NULL, NULL, SW_SHOWNORMAL);

回答1:


This is Windows version. Note, the Windows functions are Unicode UTF-16, but the output file could be ANSI or UTF-8.

#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
#include <WinINet.h>

#pragma comment(lib, "WinINet.lib")

int main()
{
    std::ofstream fout(L"c:\\test\\_test.htm", std::ios::binary);
    std::wstring url = L"https://www.stackoverflow.com/questions/29547368";
    HINTERNET hopen = InternetOpen(L"MyAppName", 
                            INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if(hopen)
    {
        DWORD flags = INTERNET_FLAG_DONT_CACHE;
        if(url.find(L"https://") == 0) 
            flags |= INTERNET_FLAG_SECURE;
        HINTERNET hinternet = InternetOpenUrl(hopen, url.c_str(), NULL, 0, flags, 0);
        if(hinternet)
        {
            char buf[1024];
            DWORD received = 0;
            while(InternetReadFile(hinternet, buf, sizeof(buf), &received))
            {
                if(!received) break;
                fout.write(buf, received);
            }
            InternetCloseHandle(hinternet);
        }
        InternetCloseHandle(hopen);
    }
    return 0;
}


来源:https://stackoverflow.com/questions/29547368/how-do-i-save-a-webpage-using-c-windows-or-linux-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!