URLOpenBlockingStreamW 到内存

URLOpenBlockingStreamW to Memory

我想下载一个文件到内存,程序过程中产生一个LoadLibrary,如何实现下载到内存 ?现在我正在输出文件的内容。

    struct ComInit
    {
        HRESULT hr;
        ComInit() : hr(::CoInitialize(nullptr)) {}
        ~ComInit() { if (SUCCEEDED(hr)) ::CoUninitialize(); }
    };

    ComInit init;

    CComPtr<IStream> pStream;

    HRESULT hr = URLOpenBlockingStreamW(nullptr, L"http://333.cf/gw.txt", &pStream, 0, nullptr);
    if (FAILED(hr))
    {
        std::cout << "could not connect, hr: 0x" << std::hex << hr << std::dec << std::endl;
        return 1;
    }

    char buffer[4096];
    do
    {
        DWORD bytesRead = 0;
        hr = pStream->Read(buffer, sizeof(buffer), &bytesRead);

        if (bytesRead > 0)
        {
            std::cout.write(buffer, bytesRead);
        }
    } while (SUCCEEDED(hr) && hr != S_FALSE);

您已经在下载到内存中。您为此使用了一个固定字节数组,您正在将其写入 std::cout。只需将其写出到另一个内存缓冲区,例如 std::vector。如果您在下载前知道文件大小,则可以预先调整矢量的大小。否则,只需在写入时让它调整大小(这对大文件来说效率不高)。

struct ComInit
{
    HRESULT hr;
    ComInit() : hr(::CoInitialize(nullptr)) {}
    ~ComInit() { if (SUCCEEDED(hr)) ::CoUninitialize(); }
};

ComInit init;
CComPtr<IStream> pStream;

HRESULT hr = URLOpenBlockingStreamW(nullptr, L"http://333.cf/gw.txt", &pStream, 0, nullptr);
if (FAILED(hr))
{
    std::cerr << "could not connect, hr: " << std::hex << std::showbase << hr << std::endl;
    return 1;
}

std::vector<char> kek;

STATSTG stat = {};
hr = pStream->Stat(&stat, STATFLAG_NONAME);
if (SUCCEEDED(hr))
    kek.reserve(stat.cbSize.QuadPart);

char buffer[1024];
DWORD bytesRead;

do
{
    hr = pStream->Read(buffer, sizeof(buffer), &bytesRead);
    if (FAILED(hr))
    {
        std::cerr << "could not read data, hr: " << std::hex << std::showbase << hr << std::endl;
        return 1;
    }

    if (bytesRead == 0)
        break;

    kek.insert(kek.end(), buffer, buffer + bytesRead);
}
while (true);

// use kek as needed...