Weird Characters is output whenever ptr is printed from CURL_WRITEFUNCTION.

I have a little problem, here is my code (I use C):

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

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
//json_object *json_obj = json_tokener_parse(ptr);
printf ("%s",(char*)ptr);

return count;

}

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

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
    curl_easy_setopt(curl, CURLOPT_USERPWD, "Firrus:password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
    curl_easy_perform(curl);



    /* always cleanup */ 
    curl_easy_cleanup(curl);


  }

  return 0;
}

The problem is that every time ptr is printed, the top three (seemingly random) characters are also displayed at the top, for example. 77D or 6DA. What do these symbols mean? How can I delete them?

+3
source share
1 answer

According to the documentation, callback functions work as follows:

, : size_t ( void * ptr, size_t size, size_t nmemb, void * userdata); libcurl, , . , ptr nmemb, . . , , . CURLE_WRITE_ERROR. 7.18.0 CURL_WRITEFUNC_PAUSE, . . Curl_easy_pause (3) .

, .

.....

userdata CURLOPT_WRITEDATA.

, . , . , curl.h: CURL_MAX_WRITE_SIZE.

, callback . , , .

:

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

typedef struct {
    size_t size;
    char *payload;
}srvresponse;

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
    //printf("%s", (char*) ptr);

    size_t realsize = size * count;
    printf("Chuncksize:%lu\n",realsize);
    srvresponse *ret = (srvresponse*)stream;
    //Increase the payload size
    ret->payload = realloc(ret->payload,ret->size + realsize + 1);
    //Copy the new data
    memcpy(&(ret->payload[ret->size]),ptr,realsize);
    //Update the size
    ret->size += realsize;
    //Terminate the string
    ret->payload[ret->size] = 0;
    printf("Read so far:%s",ret->payload);
    return realsize;

}

int main(void) {
    CURL *curl;

    srvresponse retdata;
    retdata.payload = malloc(1);//We increase the capacity later
    retdata.size = 0;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
        curl_easy_setopt(curl, CURLOPT_USERPWD, "user:pass");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&retdata);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        curl_global_cleanup();


        if (retdata.payload){
            puts(retdata.payload);
            free(retdata.payload);
        }
    }

    return 0;
}
+3

Source: https://habr.com/ru/post/1787004/


All Articles