-
Notifications
You must be signed in to change notification settings - Fork 0
Writing the software
Marcus Ottosson edited this page Jan 24, 2015
·
3 revisions
#include <stdio.h>
#include <libgen.h> // For basename()
#include <curl/curl.h>
/*
* From http://stackoverflow.com/questions/7963170/how-to-do-remove-the-last-occurrence-of-a-string-from-another-string
*/
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(int argc, char* args[]) {
// Assume a single argument
if (argc != 2) {
printf("Please enter a URL");
return 1;
}
// Declare a pointer to a CURL *easy* handle
// http://curl.haxx.se/libcurl/c/curl_easy_init.html
CURL *curl;
// If there is any error, this is the variable in which it will be stored.
// http://curl.haxx.se/libcurl/c/curl_easy_strerror.html
CURLcode res;
// This (file-handle) is what we'll use to write to disk
FILE *fp;
// Apparently, this function must be the first function call.
// http://curl.haxx.se/libcurl/c/curl_easy_init.html
curl = curl_easy_init();
if(curl) {
// We configure the `curl` struct to point
// to the first argument we passed from the
// terminal.
curl_easy_setopt(curl, CURLOPT_URL, args[1]);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
// Now that we've passed the full url, let's
// get the last part of the URL, which will
// become our file-name.
char *output = basename(args[1]);
fp = fopen(output, "wb");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
// Always cleanup
curl_easy_cleanup(curl);
}
return 0;
}