Download a file from webpage

I figured out how to download an html page and store the source code as a .txt file. Now I’m trying to do the same with other files extension, here in my example I’m trying to download a .png file from a website.

I tried this code where the image adress is http://www.example.com/image.png :

#include <wininet.h>
#include <iostream>
#include <fstream>

ofstream writeFile("img.png"); // I create my .png file

HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
HINTERNET hConnection = InternetConnectA( hInternet, "www.example.com", 80, " "," ", INTERNET_SERVICE_HTTP, 0, 0 );
HINTERNET hData = HttpOpenRequestA( hConnection, "GET", "image.png", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );

// I setup the connection

char buf[ 2048 ] ;
HttpSendRequestA( hData, NULL, 0, NULL, 0 ) ;
DWORD bytesRead = 0 ;

while( InternetReadFile( hData, buf, 2000, &bytesRead ) && bytesRead != 0 )
{
    buf[ bytesRead ] = 0 ;
    writeFile << buf << endl; // I copy the data from the website to my own file
}

HttpSendRequestA( hData, NULL, 0, NULL, 0 ) ;;

InternetCloseHandle( hData ) ;
InternetCloseHandle( hConnection ) ;
InternetCloseHandle( hInternet ) ;
writeFile.close(); // I close everything

But I can’t open the generated .png file. It’s not a valid image. When I try to open it in a text editor, it looks like any .png file (Look this) but the file is way shorter (60Ko vs. 4Ko).

Is there any other method to download a file from a website ? Why is this method creating a bad png file ?