如何使用libcurl保存图像

我想将libcurl用于涉及从网页获取图像的项目。 URL如下所示:

http://sofzh.miximages.com/c%2B%2B/image.jpg

使用命令行cURL我可以使用检索图像

$curl -o sampleimage.jpg http://sofzh.miximages.com/c%2B%2B/image.jpg 

我想知道libcurl中这段代码的等价物,因为我现在已经疯了。 我在网上得到了这个示例源,它编译和填充,但我无法在任何地方看到图像文件。

这是代码:

 #include  #include  #include  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://sofzh.miximages.com/c%2B%2B/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()的完整路径。 谢谢你! 请回答这个问题,以便我可以选择你的正确答案。 谢谢!

在公开呼叫中使用完整路径,以便您知道在哪里查看。

此外,您应该查看perror函数,这样您就可以打印出打开失败的原因 – 省去了一些麻烦。

最后一件事:将fp初始化为null,或者只有fclose(fp)才真正打开。 就目前而言,如果curl_easy_init失败,您将尝试fclose随机指针。