2011-07-11 41 views
5

我想將libcurl用於涉及從網頁獲取圖像的項目。 的URL看起來是這樣的:如何使用libcurl保存圖像

http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg

使用命令行卷曲我可以檢索使用

$curl -o sampleimage.jpg http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg 

我想知道這個代碼libcurl中的等效的,因爲我得到的圖像現在堅果。我在網上獲得了這個示例源代碼,它編譯了一些東西,但我無法在任何地方看到圖像文件。

這是代碼:

#include <iostream> 
#include <curl/curl.h> 
#include <stdio.h> 

using namespace std; 

int main(){ 
CURL *image; 
CURLcode imgresult; 
FILE *fp; 

image = curl_easy_init(); 
if(image){ 
    // Open file 
    fp = fopen("google.jpg", "wb"); 
    if(fp == NULL) cout << "File cannot be opened"; 

    curl_easy_setopt(image, CURLOPT_URL, "http://192.168.16.25/cgi-bin/viewer/video.jpg"); 
    curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, NULL); 
    curl_easy_setopt(image, CURLOPT_WRITEDATA, fp); 


    // Grab image 
    imgresult = curl_easy_perform(image); 
    if(imgresult){ 
     cout << "Cannot grab the image!\n"; 
    } 
} 

// Clean up the resources 
curl_easy_cleanup(image); 
// Close the file 
fclose(fp); 
return 0; 
} 

順便說一句,我使用的是Mac,我在編寫這個XCode的代碼具有的libcurl庫。

* 編輯: *問題修復。我只是使用了fopen()的完整路徑。謝謝你!請回答這個問題,以便我可以選擇你的答案作爲正確的答案。謝謝!

+0

在「open」調用中使用完整路徑,以便您知道去哪裏尋找。 – Mat

+0

我會試試。但是我怎麼用mac做呢?我知道如何在Windows的文件系統中完成,而不是在Mac中。謝謝。 – IBG

+0

我該如何向那些評論過的人發信息?感謝那個人,我解決了這個問題。喂墊子,請回答,以便我可以選擇你的答案。謝謝! – IBG

回答

3

在公開電話中使用完整路徑,以便您知道去哪裏尋找。

另外你應該看看perror函數,這樣你就可以打印出打開失敗的原因 - 這樣可以節省一些難題。

最後一件事:初始化fp爲空,或者只有fclose(fp)如果它真的打開。按照現狀,如果curl_easy_init失敗,您將嘗試使用fclose一個隨機指針。

+0

感謝您的答覆和其他信息! – IBG