如何使用 C++ 保存网页?Windows 或 Linux 系统
我需要知道如何在 Windows 和/或 Linux 上使用 C++ 保存网页.
I need to know how to save a webpage using C++ on a Windows and/or Linux.
第 1 步)这是我当前打开网页的代码:
ShellExecute(NULL, "open", websiteURL, NULL, NULL, SW_SHOWNORMAL);
第 2 步)这是我将打开的网页保存为 .txt 文件的步骤
Your help here.
第 3 步)这是我在将网页另存为 .txt 后关闭网页的尝试;但是,它目前不起作用.
ShellExecute(NULL, "close", websiteURL, NULL, NULL, SW_SHOWNORMAL);
推荐答案
这是 Windows 版本.请注意,Windows 函数是 Unicode UTF-16,但输出文件可以是 ANSI 或 UTF-8.
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;
}
相关文章