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