cURL / Mailing Lists / curl-library / Single Mail

curl-library

Problem with CURLOPT_WRITEDATA getting Binary data

From: Kalidoss Sivasamy <kalidoss2_at_gmail.com>
Date: Sun, 30 May 2010 01:01:59 -0500

Hello all,

I have this following code getting the binary data stored in a buffer. While
this gets all the data to the console fine (without WRITEDATA), it doesn't
get the complete data to the char buffer. WRITEFILE works fine as well.

Am I missing any options here?

Thanks,
Kal

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

#include <curl/curl.h>

struct MemoryStruct {
      char *memory;
      size_t size;
};

void *myrealloc(void *ptr, size_t size)
{
  /* There might be a realloc() out there that doesn't like reallocing
     NULL pointers, so we take care of it here */
  if(ptr)
    return realloc(ptr, size);
  else
    return malloc(size);
}

size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)data;

  mem->memory = (char *)myrealloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory) {
    memcpy(&(mem->memory[mem->size]), ptr, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;
  }

  return realsize;

}

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

  struct MemoryStruct chunk;

  chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
  chunk.size = 0; /* no data at this point */

  struct curl_slist *headers = NULL;
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();

  if(curl) {
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

    curl_easy_setopt(curl, CURLOPT_URL,"
http://www.buildeazy.com/plans/test.pdf");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    printf("Data [%s]\n", chunk.memory);

    if (chunk.memory)
          free(chunk.memory);

   }

  return 0;
}

-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2010-05-30