0

I'm using cURL in C and want to have the page header and body written to memory rather than a file:

static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
{
  int written = fwrite(ptr, size, nmemb, (FILE *)stream);
  return written;
}

This thread details doing it in C++, and this thread details doing it in GCC.

From what I can find (here and here), there is no way of doing it in MVSC - or not easily.

Surely there must be some way of doing this, if not by substituting the file stream then with some function of the cURL library? Maybe some way of getting around the pointer to a stream that is passed? I'm stumped!

Community
  • 1
  • 1
Daniel Szanto
  • 89
  • 1
  • 9

1 Answers1

1

The first question you linked shows exactly how to do it. You don't need anything fancy. If you are using C++ you're good to go with a stringstream. If not, you could just append to a buffer using plain auld memcpy.

struct buffer {
   void *mem;
   size_t size;
};

....
struct buffer b = {0};
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &b);


static size_t writeData(void *ptr, size_t size, size_t nmemb, void *data)
{
    void *mem;
    struct buffer *b = data;

    /* Save old size and try to realloc buffer. */
    size_t oldsize = b->size;
    b->size += size * nmemb;
    if (!(mem = realloc(b->mem, b->size))) {
        /* realloc failed, handle error. */
    }

    /* If realloc worked, just append. */
    b->mem = mem;
    mempy(b->mem + oldsize, ptr, nmemb * size);
}

This code is not tested but it should be reasonably easy to iron out the problems.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Fantastic thanks for that! I got it working like so: static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) { void *mem; struct buffer *b = stream; //struct buffer **pb = stream; /* Save old size and try to realloc buffer. */ size_t oldsize = b->size; b->size += size * nmemb; if (!(mem = realloc(b->mem, b->size + oldsize))) { /* realloc failed, handle error. */ return CURLE_OUT_OF_MEMORY; } /* If realloc worked, just append. */ b->mem = mem; memcpy((unsigned char*)b->mem + oldsize, ptr, nmemb * size); return nmemb; } – Daniel Szanto Mar 28 '14 at 04:51