使用 libcurl C++ 将文件下载到 Ubuntu,简单示例不起作用 [英] Downloading a file to Ubuntu with libcurl C++, simple example doesn't work

查看:33
本文介绍了使用 libcurl C++ 将文件下载到 Ubuntu,简单示例不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有 C++ 的 libcurl 将单个图像文件下载到我的 Ubuntu 机器上.

I'm trying to use libcurl with C++ to download a single image file to my Ubuntu machine.

我尝试复制并粘贴此问题中显示的简单示例:使用 libcurl 下载文件在 C/C++ 中

I tried copying and pasting the simple example shown in this question: Download file using libcurl in C/C++

#include <stdio.h>
#include <curl/curl.h>
#include <string>

using namespace std;

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    const char *url = "https://i.imgur.com/mWj0yzI.jpg";
    char outfilename[FILENAME_MAX] = "/home/my_username/test.jpg";
    curl = curl_easy_init();
    if (curl)
    {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

我希望它下载图像文件并将其保存为test.jpg"在我的机器上.但是,当我运行此程序时,test.jpg"的大小为 0 字节.显然,由于某种原因,图像没有写入文件.

I expected it to download the image file and save it as "test.jpg" on my machine. However, when I run this program, "test.jpg" is 0 bytes in size. Apparently the image didn't write to the file for some reason.

我做错了什么?

推荐答案

您的链接未指向现有文件.有了正确的链接,它对我有用.试试这个:

Your link does not point to an existing file. With a correct link it works for me. Try this:

const char *url = "https://i.imgur.com/oRtvmGT.jpg";

这篇关于使用 libcurl C++ 将文件下载到 Ubuntu,简单示例不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆