When i put this code in main and put it static it works fine but when i separate them to another class. This problem comes out. Does anybody know why?
#ifndef __PathToExile__ConnectHandler__
#define __PathToExile__ConnectHandler__
#include <curl/curl.h>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
class ConnectHandler{
public:
ConnectHandler();
size_t data_write(void* buf, size_t size, size_t nmemb, void* userp);
CURLcode curl_read(const std::string& url, std::ostream& os, long timeout = 30);
void writeWebToFile(std::string filename);
};
#endif /* defined(__PathToExile__ConnectHandler__) */
#include "ConnectHandler.h"
ConnectHandler::ConnectHandler(){
curl_global_init(CURL_GLOBAL_ALL);
}
size_t ConnectHandler::data_write(void* buf, size_t size, size_t nmemb, void* userp)
{
if(userp)
{
std::ostream& os = *static_cast<std::ostream*>(userp);
std::streamsize len = size * nmemb;
if(os.write(static_cast<char*>(buf), len)) //EROR: Thread 1: Exe_Bad_access (code = 1, address = 0x10)
return len;
}
return 0;
}
CURLcode ConnectHandler::curl_read(const std::string& url, std::ostream& os, long timeout)
{
CURLcode code(CURLE_FAILED_INIT);
CURL* curl = curl_easy_init();
if(curl)
{
if(CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &ConnectHandler::data_write))
&& CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L))
&& CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L))
&& CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FILE, &os))
&& CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout))
&& CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_URL, url.c_str())))
{
code = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
}
return code;
}
void ConnectHandler::writeWebToFile(std::string filename){
std::ofstream ofs(filename);
if(CURLE_OK == ConnectHandler::curl_read("http://www.google.com", ofs))
{
std::cout << "Successfully write web to file " << filename << std::endl;
}
}
So in the main file i call it like normal: Connecthandler c()
c.writeWebToFile("haha-masupilami.txt")
the problem occur at function size_t data_write(..) i already comment the line problem occur. Does anybody know what went wrong. 'Cause it works file when i put i static function in main file.