如何使用 C++ 保存网页?Windows 或 Linux 系统 [英] How do I save a webpage using C++? Windows or Linux System

查看:27
本文介绍了如何使用 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;
}

这篇关于如何使用 C++ 保存网页?Windows 或 Linux 系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆