0

I tried compiling both the examples on this question: Download file using libcurl in C/C++

Here's one of them:

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

the problem is that this example, when run, immediately returns and I get a blank file. Why? I modified to

if (curl)
{   
    fp = fopen(outfilename,"wb");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    fclose(fp);
} else {
    printf("error\n");
}

but I see no error. I tried compiling in both C++ and C, I get the same result on both.

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150

1 Answers1

1

I had the same issue and I fixed it by:

curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);

According to https://curl.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html, true tells the library to follow HTTP location.

czs108
  • 151
  • 4