0

I am trying to download a file from internet in C++. Hold the downloaded contents into HInternet Instance.

Also I populated the header information of HInternet instance. That is looks like

Header contents:
HTTP/1.1 200 OK
Cache-Control: no-cache
Date: Fri, 24 Nov 2017 07:00:26 GMT
Pragma: no-cache
Content-Length: 71156
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/8.0
Content-Disposition: attachment; filename=642078_3855u.zip
X-AspNet-Version: 4.0.30319

Error 0 has occurred.

Now I am trying to copied the 642088_3855u.zip file into some location.

So, I tried as,

if (bResults)
{
    do
    {
        // Check for available data.
        dwSize = 0;
        if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
        {
            dwLastError = GetLastError();
            break;
        }

        // No more available data.
        if (!dwSize)
            break;

        // Allocate space for the buffer.
        pszOutBuffer = new char[dwSize + 1];
        if (!pszOutBuffer)
        {
            bError = true;
            break;
        }

        FILE *pfDestination = NULL;
        _wfopen_s(&pfDestination, strDestinationFolder + L"\\" + L"642078_3855u.zip", L"w+b");
        if (pfDestination == NULL)
        {
            bError = true;
            break;
        }

        // Read the Data.
        ZeroMemory(pszOutBuffer, dwSize + 1);
        if (WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
            dwSize, &dwDownloaded))
        {
            fwrite(pszOutBuffer, 1, dwDownloaded, pfDestination);
        }

        // Free the memory allocated to the buffer.
        delete[] pszOutBuffer;
        fclose(pfDestination);
        // reported that there are bits to read.
        if (!dwDownloaded)
            break;

    } while (dwSize > 0);
}

I am not getting any error, actual size of zip if is 72kb but it is created zip file with 4kb and when I am trying to open zip file, I am getting error Invalid zip file.

Note that: zip file contains executable also.

any suggestion where I am doing mistake.

Thanks,

CrazyCoder
  • 772
  • 5
  • 11
  • 31
  • 1
    You should try opening the file with `ab`, not `w+b`. I think the latter creates a new file each time. – manuell Nov 24 '17 at 09:09
  • Yeah you are right ... thank you so much. :) I wasted my 2 working day on this silly issue. Thank you again. Now it is working fine in all cases. – CrazyCoder Nov 24 '17 at 10:08

0 Answers0