I'm trying to use libcurl with C++ to download a single image file to my Ubuntu machine.
I tried copying and pasting the simple example shown in this question: Download file using libcurl in C/C++
#include <stdio.h>
#include <curl/curl.h>
#include <string>
using namespace std;
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
const char *url = "https://i.imgur.com/mWj0yzI.jpg";
char outfilename[FILENAME_MAX] = "/home/my_username/test.jpg";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename,"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);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
I expected it to download the image file and save it as "test.jpg" on my machine. However, when I run this program, "test.jpg" is 0 bytes in size. Apparently the image didn't write to the file for some reason.
What am I doing wrong?