2012-05-13 5 views
0

Просто пытаюсь изучить C++. Я начинаю с скребка. Идея заключается в том, что я хочу очистить кучу страниц, применить регулярное выражение и написать свои данные в файл.C++: использование libcurl и потоков

Однако в настоящее время я застреваю, пытаясь назначить ручку curl для записи в строковую переменную. Любые указатели (советы, которые я имею в виду ...)?

#include <stdio.h> 
#include <curl/curl.h> 
#include <string> 
#include <iomanip> 
#include <boost/lexical_cast.hpp> 

// Typedefs 
using std::string;  using boost::lexical_cast; 
using std::cout; 
using std::endl; 
using std::ostringstream; 

// CURL directives 
static const string BASE_URL = "http://www.XXXXXX.com/action?page="; 
static char* USER_AGENT_STRING = "C++ Scraper"; 

// CURL variables 
static CURL* curl; 
static CURLcode res; 

     void setPageOpts(CURL* c, int count, const ostringstream stream) { 
      cout << "Got to the set opts method." << endl; 

      // Set URL 
      string new_url = BASE_URL + lexical_cast<string>(count); 
      curl_easy_setopt(curl, CURLOPT_URL, new_url.c_str()); 
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream); 
     } 

     void setConstOpts(CURL *c) { 
      // User agent string 
      curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT_STRING); 
      //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); 
     } 

     void loadCurl() { 
      int status = curl_global_init(CURL_GLOBAL_ALL); 

      if (status != 0) { 
       cout << "An error has occurred with exit status " << status << endl; 
       exit(status); 
      } 
     } 

     int main() { 
      loadCurl(); 
      curl = curl_easy_init(); 

      if(curl) { 
       setConstOpts(curl); 

       for (int i = 1; i < 2; ++i) {   
        const ostringstream stream; 

        setPageOpts(curl, i, &stream); 

        res = curl_easy_perform(curl); 

        string output = stream.get(); 
        cout << "And the data was: " << endl << endl << output << endl; 
       } 

       curl_easy_cleanup(curl); 
      } 

      // Everything went as planned 
      return 0; 
     } 

Текущие ошибки я получаю:

learn.cpp:15: warning: deprecated conversion from string constant to 'char*' 
learn.cpp: In function 'int main()': 
learn.cpp:62: error: conversion from 'const std::ostringstream*' to non-scalar type 'std::ostringstream' requested 
learn.cpp:67: error: request for member 'get' in 'stream', which is of non-class type 'const std::ostringstream*' 

Как я вижу это, я хочу, чтобы завить расположение потока в памяти, так что он может написать там. Поэтому я предположил, что мне нужно использовать символ & и передать его. Но это не работает.

ответ

2

Ваше определение:

void setPageOpts(CURL* c, int count, const ostringstream stream) 

ли, скорее всего, вызовет у вас проблем. Похоже, что вы имеете в виду, чтобы передать stream в по ссылке так, что она может быть обновлена:

void setPageOpts(CURL* c, int count, ostringstream& stream) 

(и не забудьте использовать c, когда вы передаете его в).

И тогда вместо этого:

   const ostringstream stream; 
       setPageOpts(curl, i, &stream); 

Вызов вашей функции:

 ostringstream stream; 
     setPageOpts(curl, i, stream); 

Это позволит stream обновляться.

std::ostringstream не имеет ::get(). Я думаю, что вы имели в виду:

 string output = stream.str(); 

Вы можете также найти this answer полезным, без установки CURLOPT_WRITEFUNCTION указать функцию обратного вызова, чтобы использовать свой std::ostringstream указатель, вы получите нарушение прав доступа, когда Libcurl пытается write к нему.

3

Первое предупреждение для

static char* USER_AGENT_STRING = "C++ Scraper"; 

где литерал const, поэтому указатель должен быть указателем на const char.

Вторая проблема связана с const ostringstream stream. Если поток равен const, вы не можете ничего сделать, чтобы изменить его состояние - например, чтение или запись.

Смежные вопросы