Get a page in memory
This example is a variation of the former that instead of sending the received data to stdout (which often is not what you want), this example instead stores the incoming data in a memory buffer that is enlarged as the incoming data grows.
It accomplishes this by using a write callback to receive the data.
This example uses a fixed URL string with a set URL scheme, but you can of course change this to use any other supported protocol and then get a resource from that instead.
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
5
#include <curl/curl.h>
6
7
struct MemoryStruct {
8
char *memory;
9
size_t size;
10
};
11
12
static size_t
13
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
14
{
15
size_t realsize = size * nmemb;
16
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
17
18
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
19
if(mem->memory == NULL) {
20
/* out of memory */
21
printf("not enough memory (realloc returned NULL)\n");
22
return 0;
23
}
24
25
memcpy(&(mem->memory[mem->size]), contents, realsize);
26
mem->size += realsize;
27
mem->memory[mem->size] = 0;
28
29
return realsize;
30
}
31
32
int main(void)
33
{
34
CURL *curl_handle;
35
CURLcode res;
36
37
struct MemoryStruct chunk;
38
39
chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
40
chunk.size = 0; /* no data at this point */
41
42
curl_global_init(CURL_GLOBAL_ALL);
43
44
/* init the curl session */
45
curl_handle = curl_easy_init();
46
47
/* specify URL to get */
48
curl_easy_setopt(curl_handle, CURLOPT_URL, "https://www.example.com/");
49
50
/* send all data to this function */
51
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
52
53
/* we pass our 'chunk' struct to the callback function */
54
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
55
56
/* some servers do not like requests that are made without a user-agent
57
field, so we provide one */
58
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
59
60
/* get it! */
61
res = curl_easy_perform(curl_handle);
62
63
/* check for errors */
64
if(res != CURLE_OK) {
65
fprintf(stderr, "curl_easy_perform() failed: %s\n",
66
curl_easy_strerror(res));
67
}
68
else {
69
/*
70
* Now, our chunk.memory points to a memory block that is chunk.size
71
* bytes big and contains the remote file.
72
*
73
* Do something nice with it!
74
*/
75
76
printf("%lu bytes retrieved\n", (long)chunk.size);
77
}
78
79
/* cleanup curl stuff */
80
curl_easy_cleanup(curl_handle);
81
82
free(chunk.memory);
83
84
/* we are done with libcurl, so clean it up */
85
curl_global_cleanup();
86
87
return 0;
88
}
Copied!
Last modified 1yr ago
Export as PDF
Copy link