LoginSignup
40
45

More than 5 years have passed since last update.

C/C++のlibcurl利用サンプル

Last updated at Posted at 2013-04-17

以前試したコードを無くさないうちにメモ。
C/C++でlibcurlを使ってwww.google.comからGETするサンプルです。

FreeBSD 9.1でclang/clang++を使って試してみました。

まずはC。

libcurl_test.c
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

#define MAX_BUF 65535

static char wr_buf[MAX_BUF];
static int  wr_index = 0;

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
        int segsize = size * nmemb;

        if ((wr_index + segsize) > MAX_BUF) {
                *(int *)userp = 1;
                return 0;
        }

        memcpy((void *)&wr_buf[wr_index], buffer, (size_t)segsize);

        wr_index += segsize;

        wr_buf[wr_index] = '\0';

        return segsize;
}

int main(void)
{
        CURL *curl;
        CURLcode ret;
        int wr_error = 0;

        curl = curl_easy_init();
        if (curl == NULL) {
                fprintf(stderr, "curl_easy_init failed.\n");
                return 1;
        }

        curl_easy_setopt(curl, CURLOPT_URL, "www.google.co.jp");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&wr_error);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

        //
        ret = curl_easy_perform(curl);

        printf("ret=%d (write_error=%d)\n", ret, wr_error);

        if (ret == 0) {
                printf("%s\n", wr_buf);
        }

        curl_easy_cleanup(curl);

        return 0;
}

続いてC++。

libcurl_test.cpp
#include <string> 
#include <iostream> 
#include <curl/curl.h> 

using namespace std;

size_t callbackWrite(char *ptr, size_t size, size_t nmemb, string *stream)
{
        int dataLength = size * nmemb;
        stream->append(ptr, dataLength);
        return dataLength;
}

int main()
{
        CURL *curl;
        CURLcode ret;

        curl = curl_easy_init();
        string chunk;

        if (curl == NULL) {
                cerr << "curl_easy_init() failed" << endl;
                return 1;
        }

        curl_easy_setopt(curl, CURLOPT_URL, "https://www.google.co.jp/");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callbackWrite);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
        ret = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        if (ret != CURLE_OK) {
                cerr << "curl_easy_perform() failed." << endl;
                return 1;
        }

        cout << chunk << endl;

        return 0;
}
40
45
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
45