1
0

getinmemory.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*****************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * $Id$
  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. /* to make this work under windows, use the win32-functions from the
  16. win32socket.c file as well */
  17. #include "curl/curl.h"
  18. #include "curl/types.h"
  19. #include "curl/easy.h"
  20. struct MemoryStruct {
  21. char *memory;
  22. size_t size;
  23. };
  24. size_t
  25. WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
  26. {
  27. register int realsize = size * nmemb;
  28. struct MemoryStruct *mem = (struct MemoryStruct *)data;
  29. mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
  30. if (mem->memory) {
  31. memcpy(&(mem->memory[mem->size]), ptr, realsize);
  32. mem->size += realsize;
  33. mem->memory[mem->size] = 0;
  34. }
  35. return realsize;
  36. }
  37. int main(int argc, char **argv)
  38. {
  39. CURL *curl_handle;
  40. struct MemoryStruct chunk;
  41. chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
  42. chunk.size = 0; /* no data at this point */
  43. curl_global_init(CURL_GLOBAL_DEFAULT);
  44. /* init the curl session */
  45. curl_handle = curl_easy_init();
  46. /* specify URL to get */
  47. curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.cmake.org/HTML/Index.html");
  48. /* send all data to this function */
  49. curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  50. /* we pass our 'chunk' struct to the callback function */
  51. curl_easy_setopt(curl_handle, CURLOPT_FILE, (void *)&chunk);
  52. /* get it! */
  53. curl_easy_perform(curl_handle);
  54. /* cleanup curl stuff */
  55. curl_easy_cleanup(curl_handle);
  56. /*
  57. * Now, our chunk.memory points to a memory block that is chunk.size
  58. * bytes big and contains the remote file.
  59. *
  60. * Do something nice with it!
  61. */
  62. /* For example display it... */
  63. write(1, chunk.memory, chunk.size);
  64. return 0;
  65. }