我想下载一个没有zip的GitHub存储库的zip。它只是文件夹和文件。如果我在我的网络浏览器中导航到URL,它将下载一个zip,如果我使用wget url,它将下载一个zip,但执行下面的C脚本将不会为我下载一个zip文件。
为什么这个脚本不下载zip文件?
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://github.com/miketheknight2016/SXOS_Cheats/archive/master.zip");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_perform(curl);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
如果你不告诉curl保存它下载的文件的位置,它会在控制台中打印出来。您所看到的是在控制台中打印出的zip文件。
如果您希望将输出保存到文件,则必须创建一个将大量数据写入文件的函数,并告诉curl使用CURL_OPT_WRITEFUNCTION和CURL_OPT_WRITEDATA使用该函数:
// before main
static size_t write_data_to_file(void *ptr, size_t size, size_t nmemb, void *stream)
{
return fwrite(ptr, size, nmemb, (FILE *)stream);
}
// in main before curl_easy_perform
FILE *file = fopen("myfile.zip", "wb");
// you should probably check if file is null here - that would mean it failed to open the file
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, file);
// in main after curl_easy_perform
fclose(file);
不要问我这是多么“轻松”。