gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:54 24 4
gpt4 key购买 nike

我想将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com