2011-07-11 40 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