我正在使用curl库(https://curl.haxx.se/download.html),我想从某个 pastebin(原始)链接中读取原始文本,然后将该原始数据存储在一个名为的字符串中“密码”,但是它不起作用。它仅从下面的代码链接中获取数据“ test12345” 并出于某种原因将其打印出来,但不允许我将其存储在“ password”变量中。
我认为我做错了什么,但我不确定。
Here是问题的屏幕截图:
它输出不带std :: cout的原始数据,但不将其存储在“ password”变量中。我真的很困惑
这是我的代码:
#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;*/
}
答案 0 :(得分:0)
正如super所提到的,也许您应该已经更详细地阅读了CURL文档。就您而言,您不能依赖默认的回调函数,因为该默认函数会将userdata指针解释为FILE *指针。
因此,您需要提供自己的回调函数,该函数应将一段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;
}