How to download a file with WinHTTP in C/C++?

倖福魔咒の 提交于 2019-11-27 04:40:45

Solution :

FILE * pFile; // NEW
pFile = fopen("file.bin", "w+b"); // NEW

if (bResults)
    do 
    {
        // Check for available data.
        dwSize = 0;
        if (!WinHttpQueryDataAvailable( hRequest, &dwSize))
            printf( "Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

        // Allocate space for the buffer.
        pszOutBuffer = new char[dwSize+1];



        if (!pszOutBuffer)
        {
            printf("Out of memory\n");
            dwSize=0;
        }
        else
        {
            // Read the Data.
            ZeroMemory(pszOutBuffer, dwSize+1);

            if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
                                  dwSize, &dwDownloaded))
            {
                printf( "Error %u in WinHttpReadData.\n", 
                        GetLastError());
            }
            else
            {
                            printf("%s", pszOutBuffer);
                fwrite(pszOutBuffer, (size_t)dwDownloaded, (size_t)1, pFile); // NEW

            }

            // Free the memory allocated to the buffer.
            delete [] pszOutBuffer;
        }

    } while (dwSize>0);

fclose (pFile); // NEW

Merely opening the ofstream in binary mode does not change the way that the << operators work - they will always perfform formatted output. You need to use the stream's write() function, which does unformatted output.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!