Skip to content

Instantly share code, notes, and snippets.

@keharriso
Last active February 29, 2016 18:28
Show Gist options
  • Save keharriso/3a4bd07a17ff89561a16 to your computer and use it in GitHub Desktop.
Save keharriso/3a4bd07a17ff89561a16 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <curl/curl.h>
/* ===== HELPER FUNCTIONS ================================================= */
static size_t writeToFile(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
/* ===== EXAMPLES ========================================================= */
/* Download a file from `url` and write it to a file named `fname`.
Returns NULL on success and an error message on failure. */
const char *downloadFile(const char *url, const char *fname) {
CURL *curl;
FILE *fp;
CURLcode res;
if ((curl = curl_easy_init()) && (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);
}
if (curl) {
curl_easy_cleanup(curl);
}
if (fp) {
fclose(fp);
}
return res == CURL_OK ? NULL : curl_easy_strerror(res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment