Skip to content

Instantly share code, notes, and snippets.

Created April 12, 2014 00:14
Show Gist options
  • Save anonymous/10511247 to your computer and use it in GitHub Desktop.
Save anonymous/10511247 to your computer and use it in GitHub Desktop.
This is typically how I read in an asset in a game. MMAP is your friend.
#include "Platform.h"
bool Platform::mapFile(const char* filename, uint8_t** bytes, long* length) {
FILE* fin = fopen(Platform::pathForFile(filename).c_str(), "rb");
if (!fin) {
dbgLog("error opening file '%s'", filename);
return false;
}
// seek to end, get size
fseek(fin, 0L, SEEK_END);
*length = ftell(fin);
// rewind to beginning
fseek(fin, 0L, SEEK_SET);
// map the entire file to memory
*bytes = (uint8_t*)mmap(NULL, *length, PROT_READ, MAP_SHARED, fileno(fin), 0);
// no need for file anymore
fclose(fin);
return true;
}
void Platform::unmapFile(uint8_t** bytes, long* length) {
munmap(*bytes, *length);
}
#pragma once
namespace Platform
{
bool mapFile(const char* filename, uint8_t** bytes, long* length);
void unmapFile(uint8_t** bytes, long* length);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment