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

后端 未结 3 1723
名媛妹妹
名媛妹妹 2020-11-30 09:28

I know how to download an html/txt page. For example :

//Variables 
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
vector   vFil         


        
相关标签:
3条回答
  • 2020-11-30 09:57

    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
    
    0 讨论(0)
  • 2020-11-30 10:03

    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.

    0 讨论(0)
  • 2020-11-30 10:07

    Looks like this thread on MSDN is the same and has the solution

    http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/45ccd91c-6794-4f9b-8f4f-865c76cc146d

    0 讨论(0)
提交回复
热议问题