1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * $Id: getinmemory.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
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 /* There might be a realloc() out there that doesn't like reallocing
32 NULL pointers, so we take care of it here */
34 return realloc(ptr
, size
);
40 WriteMemoryCallback(void *ptr
, size_t size
, size_t nmemb
, void *data
)
42 size_t realsize
= size
* nmemb
;
43 struct MemoryStruct
*mem
= (struct MemoryStruct
*)data
;
45 mem
->memory
= (char *)myrealloc(mem
->memory
, mem
->size
+ realsize
+ 1);
47 memcpy(&(mem
->memory
[mem
->size
]), ptr
, realsize
);
48 mem
->size
+= realsize
;
49 mem
->memory
[mem
->size
] = 0;
54 int main(int argc
, char **argv
)
58 struct MemoryStruct chunk
;
60 chunk
.memory
=NULL
; /* we expect realloc(NULL, size) to work */
61 chunk
.size
= 0; /* no data at this point */
63 curl_global_init(CURL_GLOBAL_ALL
);
65 /* init the curl session */
66 curl_handle
= curl_easy_init();
68 /* specify URL to get */
69 curl_easy_setopt(curl_handle
, CURLOPT_URL
, "http://cool.haxx.se/");
71 /* send all data to this function */
72 curl_easy_setopt(curl_handle
, CURLOPT_WRITEFUNCTION
, WriteMemoryCallback
);
74 /* we pass our 'chunk' struct to the callback function */
75 curl_easy_setopt(curl_handle
, CURLOPT_WRITEDATA
, (void *)&chunk
);
77 /* some servers don't like requests that are made without a user-agent
78 field, so we provide one */
79 curl_easy_setopt(curl_handle
, CURLOPT_USERAGENT
, "libcurl-agent/1.0");
82 curl_easy_perform(curl_handle
);
84 /* cleanup curl stuff */
85 curl_easy_cleanup(curl_handle
);
88 * Now, our chunk.memory points to a memory block that is chunk.size
89 * bytes big and contains the remote file.
91 * Do something nice with it!
93 * You should be aware of the fact that at this point we might have an
94 * allocated data block, and nothing has yet deallocated that data. So when
95 * you're done with it, you should free() it as a nice application.
101 /* we're done with libcurl, so clean it up */
102 curl_global_cleanup();