1

put the CURL result in a string and not STDOUT?

 2 years ago
source link: https://www.codesd.com/item/put-the-curl-result-in-a-string-and-not-stdout.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

put the CURL result in a string and not STDOUT?

advertisements

I have the following curl code, which make a request to website and retrieve data from it, it works well, but I want to store my data in a string and not in the output window. Any idea?

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

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://api.hostip.info/get_html.php?ip=xxx.xxx.xx.xxx");
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
    curl_easy_cleanup(curl);
  }
  return 0;
}


int http_get_response(void *buffer, size_t size, size_t rxed, char **msg_in)
{
    char *c;

    if (asprintf(&c, "%s%.*s", *msg_in, size * rxed, buffer) == -1) {
        free(*msg_in);
        msg_in = NULL;
        return -1;
    }

    free(*msg_in);
    *msg_in = c;

    return size * rxed;
}

and add the following curl option in your main

char *msg_in = calloc(1,sizeof(char));

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &msg_in);

Then you will get the message in the msg_in

EDIT

do not forget to free msg_in when it become uselless in your program

free(msg_in); msg_in = NULL;


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK