Home > Back-end >  libcurl returns CURLcode 23
libcurl returns CURLcode 23

Time:07-08

Hello I'm currently working on a simple program to download a PNG file, but there is a problem when I use libcurl library.

Actually I first confirmed that this code works fine on WSL, but if I run this code with Windows (Visual Studio), curl_easy_perform returns CURLcode 23.

I searched this error code and I now know it means WRITE_ERROR, but I have absolutely no idea why it doesn't work.

Any helps are very appreciated. Thanks in advance!

char url[100] = "http://url_to.png"; // url directs to png file.
CURL *curl = curl_easy_init();
CURLcode res;
FILE *fp;
if (curl) {
    // Open file 
    fp = fopen("./sample.png", "wb");
    if (fp == NULL) { printf("File cannot be opened\n"); }
    else {
        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);
        if (res) { printf("Cannot grab the image! Error Code: %d\n", res); // returns Error code 23 }
    }
    fclose(fp);
}
curl_easy_cleanup(curl);

CodePudding user response:

If you are using libcurl as a win32 DLL, you MUST use a CURLOPT_WRITEFUNCTION if you set this option or you will experience crashes or lucky errors CURLE_WRITE_ERROR.

 static size_t cb(void *data, size_t size, size_t nmemb, void *userp)
 {
   FILE *fp = userp;
   return fwrite(data, size, nmemb, fp);
 }

 // ...

 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb);
 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
  • Related