Memory Files?

Started by
4 comments, last by SikCiv 24 years ago
Is it possible to load a file from the Hard disk into a memory file, giving file loading functions the ability to load the file from memory as like it is reading from the HDD. For example: Say I had one huge data file with all my MP3''z bunched up, I would read the needed MP3 into a memory file, then tell the MP3 library to load the memory file (as if it was on the Hard disk). Possible?

  Downloads:  ZeroOne Realm

Advertisement
yes...=)

if you use visual c++ there is a CMemFile object you can use, but if you want to make things to have portability is it better to write your own class/functions

Ries
Yes, I''ve written my own memory file class and it works quite well. You should too.

www.gameprojects.com - Share Your Games and Other Projects
If you know your C++ streams, something like this is possible (and damned simple!) :

ifstream fileToLoad("filename.ext");
stringstream inMemoryFile;
inMemoryFile << fileToLoad.rdbuf();

Now you can manipulate inMemoryFile as if it was the original file as it should contain the entire contents of filename.ext.
I dont know where to start, is there a sample app in MSVC5 that I can go off?

  Downloads:  ZeroOne Realm

Just start with something like this

class BaseFile
{
//Don''t forget this!
virtual ~BaseFile() {}

//Reads num_bytes bytes into buffer and returns the
//number of bytes read
virtual int Read(void* buffer, int num_bytes) = 0;

//You get the idea on this
virtual int Write(const void* buffer, int num_bytes) = 0;

//And so forth. You might want routines to move the
//file pointer, return the size of the file, etc.
};

class MemFile: public BaseFile
{
//The memory to read from
char* mem;

//Number of bytes pointed to by mem
int file_size;

//Current offset into mem
int mem_ptr;

MemFile()
{
mem = 0;
file_size = mem_ptr = 0;
}

//From BaseFile
int Read(void* buffer, int num_bytes)
{
if (!mem)
return 0;

//Don''t run past the end of the memory!
num_bytes = min(num_bytes, file_size - mem_ptr);

memcpy(buffer, &mem[mem_ptr], num_bytes);

mem_ptr += num_bytes;

return num_bytes;
}

int Write(const void* buffer, int num_bytes)
{
if (!mem)
return 0;

//Don''t run past the end of the memory!
num_bytes = min(num_bytes, file_size - mem_ptr);

memcpy(&mem[mem_ptr], buffer, num_bytes);

mem_ptr += num_bytes;

return num_bytes;
}
};

I just typed this in off the top of my head, so please don''t flame me for a typo. If I made a worse mistake, then by all means...

www.gameprojects.com - Share Your Games and Other Projects

This topic is closed to new replies.

Advertisement