본문 바로가기

정보정보

curl 사용해서 긁어와서 저장하기

#ifndef URL_HANDLE_H
#define URL_HANDLE_H

#include <curl/curl.h>
#include <stdio.h>

class URL_Handle
{
private:
CURLcode rc;
CURL* ctx;
FILE* fp;

private:

public:
URL_Handle(const char* url, const char*);
~URL_Handle();
void curl_setting(const char* url);
int curl_get_data();
};


#endif

  • source

#include "Url_handle.h"

#include <string.h>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>

URL_Handle::URL_Handle(const char* url, const char* filename)
{
curl_global_init( CURL_GLOBAL_ALL );
ctx = curl_easy_init() ;

if( NULL == ctx )
{
std::cerr << "Unable to initialize cURL interface" << std::endl ;
return;
}

printf("%s\n", filename);
fp = fopen(filename, "w");

curl_setting(url);
curl_easy_setopt( ctx, CURLOPT_NOPROGRESS, 1) ;
curl_easy_setopt( ctx, CURLOPT_WRITEHEADER, stderr) ;
curl_easy_setopt( ctx, CURLOPT_WRITEDATA, fp);
}

URL_Handle::~URL_Handle()
{
curl_easy_cleanup( ctx ) ;
curl_global_cleanup() ;
fclose(fp);
}

void URL_Handle::curl_setting(const char* url)
{
curl_easy_setopt( ctx , CURLOPT_URL, url );
}

int URL_Handle::curl_get_data()
{
rc = curl_easy_perform( ctx );

if(CURLE_OK != rc)
{
std::cerr << "Error from cURL: " << curl_easy_strerror(rc)<<std::endl;
return -1;
}

return 1;
}