2013-10-16 36 views
2

我正試圖用C編寫一個程序來下載一些文件。源代碼:用於下載捲曲文件的C程序

#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; 
} 

我可以編譯它,但這是輸出,當我運行它:

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

我發現當它嘗試執行curl_easy_perform()時發生問題,但我不知道該如何處理它。

+0

什麼是curl_easy_init()返回? – dckuehn

+0

看看[這] [1]頁,它已經被討論過了。 [1]:http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-cc – Rajan

+1

,你應該檢查是否curl_easy_init的回報()是= NULL – Mali

回答

2

您需要在設置回調數據之前打開文件。 FILE*按值存儲,而不是參考。

file = fopen(name, "wb");  
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); 
+0

現在有效,謝謝! – user2886478

2

試試這個編碼。

#include <stdio.h> 
#include <curl/curl.h> 
#include <curl/types.h> 
#include <curl/easy.h> 
#include <string> 

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) { 
    size_t written = fwrite(ptr, size, nmemb, stream); 
    return written; 
} 

int main(void) { 
    CURL *curl; 
    FILE *fp; 
    CURLcode res; 
    char *url = "http://localhost/aaa.txt"; 
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt"; 
    curl = curl_easy_init(); 
    if (curl) { 
     fp = fopen(outfilename,"wb"); 
     curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/aaa.txt"); 
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 
     curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); 
     res = curl_easy_perform(curl); 
     /* always cleanup */ 
     curl_easy_cleanup(curl); 
     fclose(fp); 
    } 
    return 0; 
}