1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
9 * Example source code to show how the callback function can be used to
10 * download data into a chunk of memory instead of storing it in a file.
12 * This exact source code has not been verified to work.
19 #include <curl/curl.h>
20 #include <curl/types.h>
21 #include <curl/easy.h>
28 static void *myrealloc(void *ptr, size_t size);
30 static void *myrealloc(void *ptr, size_t size)
32 /* There might be a realloc() out there that doesn't like reallocing
33 NULL pointers, so we take care of it here */
35 return realloc(ptr, size);
41 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
43 size_t realsize = size * nmemb;
44 struct MemoryStruct *mem = (struct MemoryStruct *)data;
46 mem->memory = myrealloc(mem->memory, mem->size + realsize + 1);
48 memcpy(&(mem->memory[mem->size]), ptr, realsize);
49 mem->size += realsize;
50 mem->memory[mem->size] = 0;
55 int main(int argc, char **argv)
59 struct MemoryStruct chunk;
61 chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
62 chunk.size = 0; /* no data at this point */
64 curl_global_init(CURL_GLOBAL_ALL);
66 /* init the curl session */
67 curl_handle = curl_easy_init();
69 /* specify URL to get */
70 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://cool.haxx.se/");
72 /* send all data to this function */
73 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
75 /* we pass our 'chunk' struct to the callback function */
76 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
78 /* some servers don't like requests that are made without a user-agent
79 field, so we provide one */
80 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
83 curl_easy_perform(curl_handle);
85 /* cleanup curl stuff */
86 curl_easy_cleanup(curl_handle);
89 * Now, our chunk.memory points to a memory block that is chunk.size
90 * bytes big and contains the remote file.
92 * Do something nice with it!
94 * You should be aware of the fact that at this point we might have an
95 * allocated data block, and nothing has yet deallocated that data. So when
96 * you're done with it, you should free() it as a nice application.
102 /* we're done with libcurl, so clean it up */
103 curl_global_cleanup();