1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * $Id: getinmemory.c,v 1.5 2003/12/08 14:13:19 bagder Exp $
10 * Example source code to show how the callback function can be used to
11 * download data into a chunk of memory instead of storing it in a file.
13 * This exact source code has not been verified to work.
18 #include <curl/curl.h>
19 #include <curl/types.h>
20 #include <curl/easy.h>
28 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
30 register int realsize = size * nmemb;
31 struct MemoryStruct *mem = (struct MemoryStruct *)data;
33 mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
35 memcpy(&(mem->memory[mem->size]), ptr, realsize);
36 mem->size += realsize;
37 mem->memory[mem->size] = 0;
42 int main(int argc, char **argv)
46 struct MemoryStruct chunk;
48 chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
49 chunk.size = 0; /* no data at this point */
51 curl_global_init(CURL_GLOBAL_ALL);
53 /* init the curl session */
54 curl_handle = curl_easy_init();
56 /* specify URL to get */
57 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://cool.haxx.se/");
59 /* send all data to this function */
60 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
62 /* we pass our 'chunk' struct to the callback function */
63 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
66 curl_easy_perform(curl_handle);
68 /* cleanup curl stuff */
69 curl_easy_cleanup(curl_handle);
72 * Now, our chunk.memory points to a memory block that is chunk.size
73 * bytes big and contains the remote file.
75 * Do something nice with it!
77 * You should be aware of the fact that at this point we might have an
78 * allocated data block, and nothing has yet deallocated that data. So when
79 * you're done with it, you should free() it as a nice application.