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

后端 未结 3 1738
名媛妹妹
名媛妹妹 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
    

提交回复
热议问题