Created
March 19, 2016 07:25
-
-
Save anonymous/0faba2e7a7fde010ca92 to your computer and use it in GitHub Desktop.
load.c
This file contains 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
bool load(FILE* file, BYTE** content, size_t* length) | |
{ | |
// check if file is null | |
// initialize length and content | |
*length = 0; | |
*content = NULL; | |
if (file == NULL) | |
{ | |
// if it is we've got an error | |
return false; | |
} | |
// initialize the buffer | |
BYTE buffer[512]; | |
// iterate over the contents of the file | |
// read 512 chunks of 1 byte at a time | |
// read while it can (not 0) | |
// the update will be to read again and store in buffer | |
for(int c = fread(buffer, 1, 512, file); c != 0; c = fread(buffer, 1, 512, file)) | |
{ | |
// first iteration it will allocate memory | |
// other iterations will reallocate mem, the new size will be: | |
// old size + new bytes + 1 | |
*content = realloc(*content, *length + c + 1); | |
// check for errors allo/reallocating memory | |
if (content == NULL) | |
{ | |
return false; | |
} | |
// copy the buffer into content | |
// destination is the first byte + old bytes | |
// from buffer | |
// new bytes c | |
memcpy(*content + *length, buffer, c); | |
*length = *length + c; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment