简体   繁体   中英

Not able download file using libcurl c++

Something wrong with my following code, no error but not downloading the file.

int main(void) 
{
    CURL *curl = NULL;
    CURLcode res = CURLE_OK;
    FILE *fp;
    curl = curl_easy_init();
    if (curl)
    {
        std::string url = "https://curl.haxx.se/mail/lib-2014-03/0158.html";
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        char outfilename[FILENAME_MAX] = "C:\Installer-Release-64-bit.html";
        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;
}

And the write data function as follows

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

Couple of issues:

write_data:  stream should technically be a void*
             You can cast it to FILE* inside the function.

             Return value should be the number of bytes processed.
             You are returning the number of objects `nmemb`.
             Should be `nmemb * size`

             Note: If the return value here is not `nmemb * size` curl
             will stop reading from the socket (I think, you need to check that).

fwrite:      Does not have to write out all `nmemb` you need to check
             and retry if the amount written is less than `nmemb`.

CURLOPT_URL  Two calls to set this option.
             curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
             curl_easy_setopt(curl, CURLOPT_URL, url);  // This is invalid
                                                        // url is not char*

Backslash    "C:\Installer-Release-64-bit.html"
             The backslash is an escape character. '\I' is simply 'I'
             Thus there is no slash at the beginning here.
             You can fix this with `\\` or you can use '/' as MS API
             has accepted this as a path separator for over a decade.

main()       Current declaration is not valid.
             In C++ the valid declarations of main are:
                  int main()
                  int main(int argc, char* argv[]) 

You should check the error code on all CURL function calls and all system functions. You say there is not an error but I don't see any checks to actually validate that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM