xcode 如何使用 libcurl 保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6645550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save image using libcurl
提问by IBG
I wanted to use libcurl for a project which involves getting an image from a webpage. The URL looks like this:
我想将 libcurl 用于涉及从网页获取图像的项目。网址如下所示:
http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg
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.
我想知道 libcurl 中这段代码的等价物,因为我现在快疯了。我在网上得到了这个示例源代码,它可以编译等等,但是我在任何地方都看不到图像文件。
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.
顺便说一句,我使用的是 Mac,我正在使用具有 libcurl 库的 XCode 编译此代码。
*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!
*编辑:*问题已修复。我只是使用了 fopen() 的完整路径。谢谢马特!请回答这个问题,以便我可以选择你的作为正确答案。谢谢!
采纳答案by Mat
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.
此外,您应该查看该perror
函数,以便您可以打印打开失败的原因 - 省去了一些麻烦。
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.
最后一件事:初始化fp
为空,或者只有fclose(fp)
当它真的打开时。就目前而言,如果curl_easy_init
失败,您将尝试fclose
使用随机指针。