我试着把两个例子都编在这个问题上: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编译,我在两种语言上都得到了相同的结果。
1条答案
按热度按时间7gcisfzg1#
我遇到了同样的问题,我通过以下方法解决了它:
根据https://curl.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html,
true
告诉库跟随HTTP位置。