libcurl简单C文件下载器示例立即返回

wribegjk  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(179)

我试着把两个例子都编在这个问题上:Download file using libcurl in C/C++
这里有一个例子:

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

问题是这个例子在运行时立即返回,并且我得到一个空文件。2为什么呢?3我修改为

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

但是我没有看到错误。我试着用C++和C编译,我在两种语言上都得到了相同的结果。

7gcisfzg

7gcisfzg1#

我遇到了同样的问题,我通过以下方法解决了它:

curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);

根据https://curl.se/libcurl/c/CURLOPT_FOLLOWLOCATION.htmltrue告诉库跟随HTTP位置。

相关问题