如何从C 中的卷曲中获取原始数据

How to obtain raw data from curl in C++

本文关键字:获取 原始数据      更新时间:2023-10-16

我正在使用curl库(https://curl.haxx.se/download.html(,我想读取特定 pastebin的原始文本(RAW((链接,然后将原始数据存储在称为"密码"的字符串中,但它不起作用。它仅获取数据" test12345" (从下面的代码中的链接中(并出于某种原因将其打印出来,但不允许我将其存储在"密码"变量中。

我认为我在做错事,但我不确定。

这是问题的屏幕截图:

它在没有std :: cout的情况下输出原始数据,但不会将其存储在"密码"变量中。我真的很困惑

这是我的代码:

#define CURL_STATICLIB
#include <curl/curl.h>
#include <iostream>
#include <string>
using std::string;
int main()
{
    CURL *curl = curl_easy_init();
    string password;
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://pastebin.com/raw/95W9vsvR");
        curl_easy_setopt(curl, CURLOPT_READDATA, &password);
        curl_easy_perform(curl);
    }
    /*std::cout << password;*/
}

如Super提到的,也许您应该更详细地阅读卷曲文档。在您的情况下,您不能依靠默认回调函数,因为该默认函数将将用户数据指针解释为文件*指针。

因此,您需要提供自己的回调功能,该功能应将Web数据附加到C 字符串对象。

下面的代码似乎可以按照您想要的工作:

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

size_t  write_callback(const char* ptr, size_t size, size_t nc, std::string* stp)
{
    if (size != 1) {
        std::cerr << "write_callback() : unexpected size value: " <<
                     size << std::endl;
    }
    size_t  initialLength = stp->length();
    size_t    finalLength = initialLength;
    stp->append(ptr, nc);    // REAL WORK DONE HERE
    finalLength = stp->length();
    // must return the actual gain:
    return (finalLength - initialLength);
}

size_t  write_callback_shim(char* ptr, size_t size, size_t nmemb, void *userdata)
{
    // just a place for the cast
    size_t        rc  = 0;
    std::string*  stp = reinterpret_cast<std::string*>(userdata);
    rc = write_callback(ptr, size, nmemb, stp);
    return rc;
}

int  main(int argc, const char* argv[])
{
    CURL*  curl = curl_easy_init();
    std::string password;
    if (curl == nullptr) {
        std::cerr << "curl pointer is null." << std::endl;
    }
    else {
        curl_easy_setopt(curl, CURLOPT_URL, "https://pastebin.com/raw/95W9vsvR");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &password);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_shim);
        curl_easy_perform(curl);
    }
    std::cout << "Password set to: " << password  << std::endl;
}