cURL / Mailing Lists / curl-library / Single Mail

curl-library

Beginner trying to download a file

From: J. Anderson <lordmaiku_at_gmail.com>
Date: Sun, 14 Jun 2009 02:34:54 -0400

I'm trying to download a smallish (1.5 MB) zip file over HTTP and having a
little trouble. The file transfer appears to work correctly, but the
downloaded file is corrupted (Unexpected end of archive errors). I'm new to
libcurl, so maybe I'm just missing an option or something else simple...
anyways, here's the code I'm using:
size_t WriteFunc( void *ptr, size_t size, size_t nmemb, FILE *stream )
{
return fwrite( ptr, size, nmemb, stream );
}

size_t ReadFunc( void *ptr, size_t size, size_t nmemb, FILE *stream )
{
return fread( ptr, size, nmemb, stream );
}

void DownloadFile( const char *remotePath )
{
FILE *outFile;
CURL *curl;
CURLcode res;
long response;

outFile = fopen( "/home/user/Desktop/test.zip", "w" );
curl = curl_easy_init();
if ( curl != NULL )
{
// Check if file exists
curl_easy_setopt( curl, CURLOPT_URL, remotePath );
curl_easy_perform( curl );
res = curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &response );

if ( response >= 400 )
{
curl_easy_cleanup( curl );
fclose( outFile );
return;
}

// Fetch the file
curl_easy_reset( curl );
curl_easy_setopt( curl, CURLOPT_URL, remotePath );
curl_easy_setopt( curl, CURLOPT_WRITEDATA, outFile );
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, WriteFunc );
curl_easy_setopt( curl, CURLOPT_READFUNCTION, ReadFunc );

res = curl_easy_perform( curl );

// cURL error?
if ( res != CURLE_OK )
{
curl_easy_cleanup( curl );
fclose( outFile );

return;
}

curl_easy_cleanup( curl );
fclose( outFile );
}
}

This code is largely taken from the sample at
http://curl.haxx.se/lxr/source/docs/examples/curlgtk.c. No errors are
returned and setting CURLOPT_VERBOSE to 1 doesn't reveal anything. I've
already confirmed that the file on the server is not corrupt (downloading it
through a browser or with curl in the terminal works fine). The file this
code downloads is very slightly larger than the original file (larger by
perhaps a few hundred bytes). So, what am I missing here?

Thanks!
Received on 2009-06-14