//只需要传入一个url就可以了
#include <curl/curl.h>
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream){
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
//last_7_char
const String last_7_char(const String s){
char *last_7_char;
last_7_char = malloc(sizeof(char) * 8);
if(strlen(s) < 7){
return s;
}else{
for(int i = 0; i < 7; i++){
last_7_char[i] = s[strlen(s) - 7 + i];
}
return last_7_char;
}
}
//fuction
void curl_download_data(const char *download_url){
const char *download_file_name = last_7_char(download_url);
FILE *file = fopen(download_file_name, "wb");
CURL *curl_handle;
curl_global_init(CURL_GLOBAL_ALL);
//init the curl session
curl_handle = curl_easy_init();
//set url to get here
curl_easy_setopt(curl_handle, CURLOPT_URL, download_url);
//send all data to the function
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
if(file != NULL){
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, file);
curl_easy_perform(curl_handle);
}
fclose(file);
//cleanup curl stuff
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
}
//main
int main(int argc, char **argv){
if(argc !=1){
fprintf(stderr, "ERROR");
}else
curl_download_data(argc[1]);
return 0;
}
////////////////////////////////////////////////////////////////////////
1.安装libcurl 否则没有头文件#include <curl/curl.h>
2.更改vscode setting.json "code-runner.exector.Map":{
"c": "cd $dir && gcc *.c -lcurl -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
} 否则无法通过编译, 需添加curl --- gcc -o main *.c -lcurl