问题描述
嗨,我正在尝试为我的项目测试 libcurl,但是当我想下载测试文件时出现错误:
ERROR : UnkNown error
但没有理由发生, 我的代码:
#include <stdio.h>
#include <curl/curl.h>
int main(int argc,char **argv) {
CURL *curl;
FILE *fp;
char name[30] = {"Test"};
char link[100] = {"ipv4.download.thinkbroadband.com/5MB.zip"};
CURLcode error;
int result;
fp = fopen(name,"Wb");
curl = curl_easy_init();
curl_easy_setopt;(curl,CURLOPT_URL,argv[1] );
curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
curl_easy_setopt(curl,CURLOPT_FAILONERROR,1L);
curl_easy_perform(curl);
result = curl_easy_perform(curl);
if (result = CURLE_OK)
printf("Sucessful download !");
else
printf("Could not download,ERROR : %s \n",curl_easy_strerror(error));
printf("%s",error);
fclose(fp);
curl_easy_cleanup(curl);
}
你知道为什么吗?!
解决方法
完全猜测 - 但它是否与您的代码调用 curl_easy_perform(curl);
两次而不是一次有关?
这看起来很可疑:
curl_easy_perform(curl);
result = curl_easy_perform(curl);
不应该只是:
result = curl_easy_perform(curl);
另外,link
上不应该有 http 前缀吗?
char link[100] = {"http://ipv4.download.thinkbroadband.com/5MB.zip"};
,
关于您的代码缩进,至少在您的 else 路径中缺少大括号。这意味着无论结果值如何,都会执行最后一个 printf... 如果您像这样添加大括号,它会按预期工作吗?当然,连同 selbie 和 Emanuel P 所述的其他建议......
if (result == CURLE_OK) {
printf("Sucessful download !");
} else {
printf("Could not download,ERROR : %s \n",curl_easy_strerror(error));
printf("%s",error);
}
,
代码中有一堆错误。
-
fopen
的参数应该是小写“w”。 - 您同时声明
error
和result
,但只能使用一个。 - 此行中间有一个分号:
curl_easy_setopt;(curl,CURLOPT_URL,argv[1] );
结合已经提到的内容,这应该有效:
#include <stdio.h>
#include <curl/curl.h>
int main(int argc,char **argv) {
if(argc < 2) {
puts("URL not given");
return 1;
}
CURL *curl;
FILE *fp;
char name[30] = {"Test"};
char link[100] = {"ipv4.download.thinkbroadband.com/5MB.zip"};
CURLcode result;
fp = fopen(name,"w");
curl = curl_easy_init();
curl_easy_setopt(curl,argv[1] );
curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
curl_easy_setopt(curl,CURLOPT_FAILONERROR,1L);
result = curl_easy_perform(curl);
if (result == CURLE_OK)
printf("Sucessful download !");
else
printf("Could not download,curl_easy_strerror(result));
fclose(fp);
curl_easy_cleanup(curl);
return 0;
}
不要忘记将 URL 作为参数传递,因为您实际上并未使用 link
并且不检查 argc
。我建议你学习如何使用调试器。