Skip to content

Instantly share code, notes, and snippets.

Created March 19, 2016 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/0faba2e7a7fde010ca92 to your computer and use it in GitHub Desktop.
Save anonymous/0faba2e7a7fde010ca92 to your computer and use it in GitHub Desktop.
load.c
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