将curl执行的输出保存到向量在 c++
正如我的标题所说,我想将curl执行的输出保存到向量中。 能给我一个示例代码吗? 我能够将它保存到c中的结构中。但我想将它保存到 C++ 中的向量中,而且我对 C++ 有点不舒服。
vector<string> contents;
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int numbytes = size*nmemb;
char lastchar = *((char *) ptr + numbytes - 1);
*((char *) ptr + numbytes - 1) = '\0';
contents.push_back((char *)ptr);
*((char *) ptr + numbytes - 1) = lastchar; // Might not be necessary.
return size*nmemb;
}
int main(int argc, char *argv[])
{
vector<string>::iterator i;
CURL* curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl,CURLOPT_URL, argv[1]);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res == 0){
for(i=contents.begin();i!=contents.end();i++)
cout << *i << endl;
}else
cerr << "Error: " << res << endl;
}
return 0;
}
as my title says, i would like to save the output of a curl perform to a vector..
can any1 please give me a sample code?
i was able to save it into a structure in c. but i want to save it to a vector that too in c++ and i'm a little unconfortable with c++.
vector<string> contents;
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int numbytes = size*nmemb;
char lastchar = *((char *) ptr + numbytes - 1);
*((char *) ptr + numbytes - 1) = '\0';
contents.push_back((char *)ptr);
*((char *) ptr + numbytes - 1) = lastchar; // Might not be necessary.
return size*nmemb;
}
int main(int argc, char *argv[])
{
vector<string>::iterator i;
CURL* curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl,CURLOPT_URL, argv[1]);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res == 0){
for(i=contents.begin();i!=contents.end();i++)
cout << *i << endl;
}else
cerr << "Error: " << res << endl;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道curl,所以我假设设置代码是正确的。因此,您想要的是回调函数,将接收到的每个数据块的字符串添加到字符串向量中。这还假设返回的数据是 8 位字符。
对 string() 的“调用”实际上构造了一个用指针和数据长度初始化的字符串对象。
I don't know curl, so I'm going to assume the setup code is correct. So what you want is the callback function to add a string for each block of data received to a vector of strings. This also assumes that the data coming back is 8-bit characters.
the "call" to string() actually constructs a string object initialized with a pointer and data length.
尝试cURLpp。这是可能有用的示例。
Try cURLpp. Here's an example that might be useful.
这就是您可能正在寻找的内容:
我相当确定您不想写入 CURL 库传递给您的
void *ptr
。而且看起来您正在用'\0'
覆盖内存地址的最后一个字符,然后在推送到向量后将原始值放回原处。我不确定这是否会按预期工作。Here's what you're probably looking for:
I'm fairly sure you don't want to write to the
void *ptr
you're passed by the CURL library. And it also looks like you are overwriting the last char of the memory address with'\0'
, then putting the original value back in there after pushing to the vector. I'm not sure this will work as expected.