]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/curl/docs/examples/getinmemory.c
hello world
[icculus/iodoom3.git] / neo / curl / docs / examples / getinmemory.c
1 /*****************************************************************************
2  *                                  _   _ ____  _     
3  *  Project                     ___| | | |  _ \| |    
4  *                             / __| | | | |_) | |    
5  *                            | (__| |_| |  _ <| |___ 
6  *                             \___|\___/|_| \_\_____|
7  *
8  * $Id: getinmemory.c,v 1.5 2003/12/08 14:13:19 bagder Exp $
9  *
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.
12  *
13  * This exact source code has not been verified to work.
14  */
15
16 #include <stdio.h>
17
18 #include <curl/curl.h>
19 #include <curl/types.h>
20 #include <curl/easy.h>
21
22 struct MemoryStruct {
23   char *memory;
24   size_t size;
25 };
26
27 size_t
28 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
29 {
30   register int realsize = size * nmemb;
31   struct MemoryStruct *mem = (struct MemoryStruct *)data;
32   
33   mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
34   if (mem->memory) {
35     memcpy(&(mem->memory[mem->size]), ptr, realsize);
36     mem->size += realsize;
37     mem->memory[mem->size] = 0;
38   }
39   return realsize;
40 }
41
42 int main(int argc, char **argv)
43 {
44   CURL *curl_handle;
45
46   struct MemoryStruct chunk;
47
48   chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
49   chunk.size = 0;    /* no data at this point */
50
51   curl_global_init(CURL_GLOBAL_ALL);
52
53   /* init the curl session */
54   curl_handle = curl_easy_init();
55
56   /* specify URL to get */
57   curl_easy_setopt(curl_handle, CURLOPT_URL, "http://cool.haxx.se/");
58
59   /* send all data to this function  */
60   curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
61
62   /* we pass our 'chunk' struct to the callback function */
63   curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
64
65   /* get it! */
66   curl_easy_perform(curl_handle);
67
68   /* cleanup curl stuff */
69   curl_easy_cleanup(curl_handle);
70
71   /*
72    * Now, our chunk.memory points to a memory block that is chunk.size
73    * bytes big and contains the remote file.
74    *
75    * Do something nice with it!
76    *
77    * You should be aware of the fact that at this point we might have an
78    * allocated data block, and nothing has yet deallocated that data. So when
79    * you're done with it, you should free() it as a nice application.
80    */
81
82   return 0;
83 }