Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

SikCiv

Memory Files?

This topic is 6696 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!