C程序下载文件与curl [英] C program for downloading files with curl
本文介绍了C程序下载文件与curl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用C写一个程序来下载一些文件。源代码:
I am trying to write a program in C to download some files. The source code:
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <curl/easy.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(){
if(curl_global_init(CURL_GLOBAL_ALL)){
printf("curl error. Exiting.\n");
return 1;
}
char links[3][100] = {
"http://download.freeroms.com/nes_roms/08/big_nose_the_caveman.zip",
"http://download.freeroms.com/nes_roms/02/contra.zip",
"http://download.freeroms.com/nes_roms/08/super_mario_bros._(usajapan).zip"};
int n = 0, k = 0;
char *lastslash;
char* name;
CURL *handle = curl_easy_init();
CURLcode res;
FILE *file;
while(n<3){
lastslash = strrchr(links[n], '/');
name = lastslash ? lastslash + 1 : links[n];
printf("\nURL: %s\n", links[n]);
printf("Filename: %s\n", name);
curl_easy_setopt(handle, CURLOPT_URL, links[n]);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, file);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
file = fopen(name, "wb");
res = curl_easy_perform(handle);
fclose(file);
n++;
}
curl_easy_cleanup(handle);
return 0;
}
我可以编译它,但这是我运行时的输出: / p>
I can compile it, but this is the output when I run it :
URL: http://download.freeroms.com/nes_roms/08/big_nose_the_caveman.zip
Filename: big_nose_the_caveman.zip
Segmentation fault (core dumped)
我的编译器设置:gcc dl.c -lcurl -o dl
My compiler setting: gcc dl.c -lcurl -o dl
我发现当尝试执行curl_easy_perform()时会出现问题,但我不知道该怎么处理。
I found out that the problem occurs when it tries to execute curl_easy_perform(), but I don't know what to do with it.
推荐答案
您需要在设置回调数据之前打开该文件。 FILE *
按值存储,而不是引用。
You need to open the file before you set the callback data. The FILE*
is stored by value, not reference.
file = fopen(name, "wb");
curl_easy_setopt(handle, CURLOPT_WRITEDATA, file);
这篇关于C程序下载文件与curl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文