使用libcurl c++无法下载文件

3

我的以下代码有问题,没有错误但是不能下载文件。

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;
}

以下是写数据函数的代码:
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

2
"C:\Installer-Release-64-bit.html" - 尝试转义那个反引号。毕竟这是Windows。为了好玩,尝试遵守Spencer的第六戒律,而不是盲目地假设fopen起作用。假设是万恶之源... - WhozCraig
1
尝试打开输出文件后测试fp - 检查函数返回值以确保代码的可靠性,这样就可以知道哪里出了问题。 - Brian Sidebotham
不检查标准(或API)函数的返回值是一个非常糟糕的习惯。 - SergeyA
好的,让我检查所有函数的返回值。 - Mukesh Bharsakle
1个回答

1
一些问题:
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[]) 

你应该检查所有 CURL 函数调用和所有系统函数的错误代码。你说没有错误,但我没有看到任何检查来实际验证它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接