Skip to content

Instantly share code, notes, and snippets.

@Junch
Created September 18, 2018 07:35
Show Gist options
  • Select an option

  • Save Junch/50b4c1f190012165b0995ab0ea927951 to your computer and use it in GitHub Desktop.

Select an option

Save Junch/50b4c1f190012165b0995ab0ea927951 to your computer and use it in GitHub Desktop.
read a whole binary file to buffer
// https://bytefreaks.net/programming-2/c/cc-full-example-of-reading-a-whole-binary-file-to-buffer
struct binary_data_t
{
long size;
void *data;
binary_data_t() : size(0), data(nullptr) {}
~binary_data_t() { delete[] data; }
};
binary_data_t *read_file(const char *filename)
{
binary_data_t *binary_data = new binary_data_t;
if (binary_data != NULL)
{
binary_data->size = 0;
// Open the file for reading in binary mode
FILE *fIn = fopen(filename, "rb");
if (fIn != NULL)
{
// Go to the end of the file
const int fseek_end_value = fseek(fIn, 0, SEEK_END);
if (fseek_end_value != -1)
{
// Get the current position in the file (in bytes)
long position = ftell(fIn);
if (position != -1)
{
// Go back to the beginning of the file
const int fseek_set_value = fseek(fIn, 0, SEEK_SET);
if (fseek_set_value != -1)
{
// Allocate enough space to read the whole file
// void *buffer = malloc(position);
void *buffer = new char[position];
if (buffer != NULL)
{
// Read the whole file to buffer
const long size = fread(buffer, 1, position, fIn);
if (size == position)
{
binary_data->size = position;
binary_data->data = buffer;
fclose(fIn);
return binary_data;
}
// free(buffer);
delete[] buffer;
}
}
}
}
fclose(fIn);
}
delete binary_data;
}
return nullptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment