Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...