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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With