Last active
May 29, 2019 05:58
-
-
Save vanessaaleung/645289f5876f9cc32d42dbd02fd14e62 to your computer and use it in GitHub Desktop.
WriteMemoryCallback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <curl/curl.h> | |
//struct in C is similar to class | |
struct MemoryStruct { | |
char *memory; | |
size_t size; //size_t is an unsigned integer type of at least 16 bit | |
}; | |
/*Callback means any executable code taht is passed as an argument, which is expected | |
to execute the argument at a given time */ | |
static size_t | |
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) | |
{ | |
size_t realsize = size * nmemb; | |
struct MemoryStruct *mem = (struct MemoryStruct *)userp; | |
//realloc(pointer to data, new size) | |
//mem->memory means getting the member called `memory` from struct `mem` points to | |
char *ptr = realloc(mem->memory, mem->size + realsize + 1); | |
if(ptr == NULL) { | |
/* out of memory! */ | |
printf("not enough memory (realloc returned NULL)\n"); | |
return 0; | |
} | |
mem->memory = ptr; | |
//memcpy(destination, source, number of bytes) | |
memcpy(&(mem->memory[mem->size]), contents, realsize); | |
mem->size += realsize; | |
mem->memory[mem->size] = 0; | |
return realsize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment