1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
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.
20 #include <curl/curl.h>
21 #include <curl/types.h>
22 #include <curl/easy.h>
29 static void *myrealloc(void *ptr, size_t size);
31 static void *myrealloc(void *ptr, size_t size)
33 /* There might be a realloc() out there that doesn't like reallocing
34 NULL pointers, so we take care of it here */
36 return realloc(ptr, size);
42 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
44 size_t realsize = size * nmemb;
45 struct MemoryStruct *mem = (struct MemoryStruct *)data;
47 mem->memory = myrealloc(mem->memory, mem->size + realsize + 1);
49 memcpy(&(mem->memory[mem->size]), ptr, realsize);
50 mem->size += realsize;
51 mem->memory[mem->size] = 0;
56 int main(int argc, char **argv)
60 struct MemoryStruct chunk;
62 chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
63 chunk.size = 0; /* no data at this point */
65 curl_global_init(CURL_GLOBAL_ALL);
67 /* init the curl session */
68 curl_handle = curl_easy_init();
70 /* specify URL to get */
71 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://cool.haxx.se/");
73 /* send all data to this function */
74 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
76 /* we pass our 'chunk' struct to the callback function */
77 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
79 /* some servers don't like requests that are made without a user-agent
80 field, so we provide one */
81 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
84 curl_easy_perform(curl_handle);
86 /* cleanup curl stuff */
87 curl_easy_cleanup(curl_handle);
90 * Now, our chunk.memory points to a memory block that is chunk.size
91 * bytes big and contains the remote file.
93 * Do something nice with it!
95 * You should be aware of the fact that at this point we might have an
96 * allocated data block, and nothing has yet deallocated that data. So when
97 * you're done with it, you should free() it as a nice application.
103 /* we're done with libcurl, so clean it up */
104 curl_global_cleanup();