Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Created October 6, 2016 08:20
Show Gist options
  • Save vurdalakov/6dae14b2d5c090e1ee5b368e610f3fd6 to your computer and use it in GitHub Desktop.
Save vurdalakov/6dae14b2d5c090e1ee5b368e610f3fd6 to your computer and use it in GitHub Desktop.
Read to and write from a binary file
#include <stdio.h>
// Reads binary file and returns its content in a byte array.
// NOTE: it's caller responsibility to free returned array with "delete[]".
inline unsigned char* readFile(const char* fileName, long* fileSizeToReturn)
{
// open file
FILE* file = fopen(fileName, "rb");
if (NULL == file)
{
return NULL;
}
// get file size
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
// create byte array
unsigned char* buffer = new unsigned char[fileSize];
// read file to buffer
fseek(file, 0, SEEK_SET);
fread(buffer, 1, fileSize, file);
// close file
fclose(file);
// return file size if needed
if (fileSizeToReturn != NULL)
{
*fileSizeToReturn = fileSize;
}
// return file content
return buffer;
}
// Writes a byte array to a file.
inline BOOL writeFile(const char* fileName, unsigned char* buffer, long bufferSize)
{
// open file
FILE* file = fopen(fileName, "wb");
if (NULL == file)
{
return FALSE;
}
// write buffer to file
fwrite(buffer, 1, bufferSize, file);
// close file
fclose(file);
return TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment