c++ - 如何使用 libcurl 保存图像

标签 c++ c xcode curl libcurl

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

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

使用命令行 cURL,我可以使用以下方法检索图像

$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() 使用了完整路径。谢谢垫!请回答问题,以便我选择您的问题作为正确答案。谢谢!

最佳答案

在公开调用中使用完整路径,以便您知道要查找的位置。

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

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

关于c++ - 如何使用 libcurl 保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6645550/

相关文章:

C++/VS 2010 : Bug(s) occur only when running without a debugger

c++ - 英特尔 SIMD 指令加速

c# - 将图像效果(灰度)应用到屏幕(PC监视器)

c - 理解 C 中的 For 循环

c++ - 使用散列合并全局内存写入

c - 处理字符串的算法

ios - 使用未解析的标识符 'FIRInstanceIDAPNSTokenTypeSandbox'

ios - 即使已发布 CIImageRefs,CIContext 内存泄漏

c++ - 从哪里获得纯 C++ Lame MP3 编码器 - PCM 到 MP3 的示例?

iOS:使用 .xcconfig 文件指定代码签名身份