1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2015, 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 https://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 ***************************************************************************/
23 * Shows how the write callback function can be used to download data into a
24 * chunk of memory instead of storing it in a file.
32 #include <curl/curl.h>
40 WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
42 size_t realsize = size * nmemb;
43 struct MemoryStruct *mem = (struct MemoryStruct *)userp;
45 mem->memory = realloc(mem->memory, mem->size + realsize + 1);
46 if(mem->memory == NULL) {
48 printf("not enough memory (realloc returned NULL)\n");
52 memcpy(&(mem->memory[mem->size]), contents, realsize);
53 mem->size += realsize;
54 mem->memory[mem->size] = 0;
64 struct MemoryStruct chunk;
66 chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
67 chunk.size = 0; /* no data at this point */
69 curl_global_init(CURL_GLOBAL_ALL);
71 /* init the curl session */
72 curl_handle = curl_easy_init();
74 /* specify URL to get */
75 curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.example.com/");
77 /* send all data to this function */
78 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
80 /* we pass our 'chunk' struct to the callback function */
81 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
83 /* some servers don't like requests that are made without a user-agent
84 field, so we provide one */
85 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
88 res = curl_easy_perform(curl_handle);
90 /* check for errors */
92 fprintf(stderr, "curl_easy_perform() failed: %s\n",
93 curl_easy_strerror(res));
97 * Now, our chunk.memory points to a memory block that is chunk.size
98 * bytes big and contains the remote file.
100 * Do something nice with it!
103 printf("%lu bytes retrieved\n", (long)chunk.size);
106 /* cleanup curl stuff */
107 curl_easy_cleanup(curl_handle);
111 /* we're done with libcurl, so clean it up */
112 curl_global_cleanup();