Home > OS >  How to download a zip file from a github repo using libcurl?
How to download a zip file from a github repo using libcurl?

Time:09-13

I have upload a zip file compressed with WinRAR containing a txt file into my github test Repo, how I could download the zip file using curl?

I tried:

    static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
    {
      size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
      return written;
    }
    
    void Download(std::string url)
    {
      CURL *curl_handle;
      static const char *pagefilename = "data.zip";
      FILE *pagefile;
    
      curl_global_init(CURL_GLOBAL_ALL);
    
      /* init the curl session */ 
      curl_handle = curl_easy_init();
    
      /* set URL to get here */ 
      curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
    
      /* Switch on full protocol/debug output while testing */ 
      curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
    
      /* disable progress meter, set to 0L to enable and disable debug output */ 
      curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
    
      /* send all data to this function  */ 
      curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
    
      /* open the file */ 
      pagefile = fopen(pagefilename, "wb");
      if(pagefile) {
    
        /* write the page body to this file handle */ 
        curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
    
        /* get it! */ 
        CURLCode res;
        res = curl_easy_perform(curl_handle);
    
        /* close the header file */ 
        fclose(pagefile);
      }
    
      /* cleanup curl stuff */ 
      curl_easy_cleanup(curl_handle);
    
      curl_global_cleanup();
    
      return;
    }


    Download("https://github.com/R3uan3/test/files/9544940/test.zip");

CURLCode res return (CURLE_OK) but it create a file data.zip of 0 bytes, what's wrong?

CodePudding user response:

The issue

I checked with

curl -I https://github.com/R3uan3/test/files/9544940/test.zip

It gets

HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...

In other words: this is a redirect and you did not ask libcurl to follow redirects - so you only get that first response stored (which has a zero byte body).

The fix

You can make libcurl follow the redirect by adding this line to your code:

curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
  • Related