• Advertisement

Archived

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

Memory Files?

This topic is 6513 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
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

Share this post


Link to post
Share on other sites
Yes, I''ve written my own memory file class and it works quite well. You should too.

Share this post


Link to post
Share on other sites
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
I dont know where to start, is there a sample app in MSVC5 that I can go off?

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