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.
17 #include <curl/curl.h>
26 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
28 size_t realsize = size * nmemb;
29 struct MemoryStruct *mem = (struct MemoryStruct *)data;
31 mem->memory = realloc(mem->memory, mem->size + realsize + 1);
32 if (mem->memory == NULL) {
34 printf("not enough memory (realloc returned NULL)\n");
38 memcpy(&(mem->memory[mem->size]), ptr, realsize);
39 mem->size += realsize;
40 mem->memory[mem->size] = 0;
46 int main(int argc, char **argv)
50 struct MemoryStruct chunk;
52 chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
53 chunk.size = 0; /* no data at this point */
55 curl_global_init(CURL_GLOBAL_ALL);
57 /* init the curl session */
58 curl_handle = curl_easy_init();
60 /* specify URL to get */
61 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.example.com/");
63 /* send all data to this function */
64 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
66 /* we pass our 'chunk' struct to the callback function */
67 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
69 /* some servers don't like requests that are made without a user-agent
70 field, so we provide one */
71 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
74 curl_easy_perform(curl_handle);
76 /* cleanup curl stuff */
77 curl_easy_cleanup(curl_handle);
80 * Now, our chunk.memory points to a memory block that is chunk.size
81 * bytes big and contains the remote file.
83 * Do something nice with it!
85 * You should be aware of the fact that at this point we might have an
86 * allocated data block, and nothing has yet deallocated that data. So when
87 * you're done with it, you should free() it as a nice application.
90 printf("%lu bytes retrieved\n", chunk.size);
95 /* we're done with libcurl, so clean it up */
96 curl_global_cleanup();