How to save image using libcurl

为君一笑 提交于 2019-12-09 12:09:49

问题


I wanted to use libcurl for a project which involves getting an image from a webpage. The URL looks like this:

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

Using command-line cURL I can retrieve the image using

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

I want to know the equivalent of this code in libcurl because I'm getting nuts right now. I got this sample source on the net, and it compiles and stuff, but I can't see the image file anywhere.

This is the code:

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

BTW I'm using a Mac and I'm compiling this code on XCode which has a libcurl library.

*EDIT:*Problem fixed. I just used a full path for the fopen(). Thanks Mat! Please answer the question so that I can choose yours as the correct answer. Thanks!


回答1:


Use a full path in the open call so that you know where to look.

Also you should look at the perror function so you can print the reason why the open fails when it does - saves a few headaches.

Last thing: initialize fp to null, or only fclose(fp) if it was really open. As it stands, if curl_easy_init fails, you'll attempt to fclose a random pointer.



来源:https://stackoverflow.com/questions/6645550/how-to-save-image-using-libcurl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!