I'm using the following function to download files from a server.
void downloadFile(const char* url, const char* fname) {
CURL *curl;
FILE *fp;
CURLcode res;
curl = curl_easy_init();
if (curl){
fp = fopen(fname, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
}
Which is used like this:
downloadFile("http://servera.com/filea.tar.gz","filea.tar.gz");
How do I add error checking into this, so if filea.tar.gz
isn't available or servera.com
can't be reached, I can display my chosen error messages.
UPDATE I've added:
cout << res;
to the code, but this always returns 0
The server returns a 'file not found' message and that is being downloaded. Anyway around this? I want to get an error if the specified file is not found or not reachable.. Thanks
UPDATE The following is now showing a human readable error message:
void downloadFile(const char* url, const char* fname) {
CURL *curl;
FILE *fp;
CURLcode res;
curl = curl_easy_init();
if (curl){
fp = fopen(fname, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
res = curl_easy_perform(curl);
cout << curl_easy_strerror(res);
curl_easy_cleanup(curl);
fclose(fp);
}
}
Now I can get the error code, I should be able to trap this better. Thanks to @YSC & @Daniel Stenberg