1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
22 /* Example source code to show how the callback function can be used to
23 * download data into a chunk of memory instead of storing it in a file.
30 #include <curl/curl.h>
39 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
41 size_t realsize = size * nmemb;
42 struct MemoryStruct *mem = (struct MemoryStruct *)data;
44 mem->memory = realloc(mem->memory, mem->size + realsize + 1);
45 if (mem->memory == NULL) {
47 printf("not enough memory (realloc returned NULL)\n");
51 memcpy(&(mem->memory[mem->size]), ptr, realsize);
52 mem->size += realsize;
53 mem->memory[mem->size] = 0;
63 struct MemoryStruct chunk;
65 chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
66 chunk.size = 0; /* no data at this point */
68 curl_global_init(CURL_GLOBAL_ALL);
70 /* init the curl session */
71 curl_handle = curl_easy_init();
73 /* specify URL to get */
74 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.example.com/");
76 /* send all data to this function */
77 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
79 /* we pass our 'chunk' struct to the callback function */
80 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
82 /* some servers don't like requests that are made without a user-agent
83 field, so we provide one */
84 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
87 curl_easy_perform(curl_handle);
89 /* cleanup curl stuff */
90 curl_easy_cleanup(curl_handle);
93 * Now, our chunk.memory points to a memory block that is chunk.size
94 * bytes big and contains the remote file.
96 * Do something nice with it!
98 * You should be aware of the fact that at this point we might have an
99 * allocated data block, and nothing has yet deallocated that data. So when
100 * you're done with it, you should free() it as a nice application.
103 printf("%lu bytes retrieved\n", (long)chunk.size);
108 /* we're done with libcurl, so clean it up */
109 curl_global_cleanup();