Read bytes from a memory mapped file
-
Hi everybody. I have a problem. I have a file mapped in memory, and a pointer to section of that file, and i need to read n bytes from the file in memory begining in the pointer. If anybody can helpme i will be gratefull.
If the file's memory mapped, then you treat it exactly like memory - so 'reading n bytes' from the file is simply a memcpy(). If you want to emulate file-like behaviour, try something like (untested code!):
// Constants, you'll need to set these up. Ideally you'd wrap these in a class somewhere
// and treat them like a FILE* object; this example only supports one 'open' file
const char* gFileBase = address at the beginning of your memory mapped file;
size_t gFileSize = size of the file that was memory mapped;size_t filePtr = 0;
int memfread(void* destination, size_t numBytes)
{
// Clamp to the end of the 'file'.
size_t bytesRemaining = gFileSize - filePtr;
if (numBytes > bytesRemaining)
numBytes = bytesRemaining;// Copy the number of bytes requested out. memcpy(destination, gFileBase + filePtr, numBytes); // Move the virtual file pointer on. filePtr += numBytes; return numBytes;
}
Something like that anyway - you can hopefully see how you might implement memfseek() and so forth. Of course, ideally you'd reap the most benefits from a memory mapped file simpply by treating it pure memory. For example, if your file was an array of Foo structures:
// Get the base of the foo array.
Foo* fooArray = reinterpret_cast<Foo*>(gFileBase);
// use fooArray as if you'd loaded them normally
// any changes you make are reflected on disk automatically.
// e.g. things like "foo[12].bar = 12;" and so forthMatt Godbolt Engineer, ProFactor Software StyleManager project -- modified at 7:06 Saturday 17th September, 2005
-
Hi everybody. I have a problem. I have a file mapped in memory, and a pointer to section of that file, and i need to read n bytes from the file in memory begining in the pointer. If anybody can helpme i will be gratefull.
Create a class that has is initialized with a pointer to that section and it's size. Every read request will increase the pointer by the amount of bytes read. If that amount gets bigger than the section's size, the EOF is reached. Don't try it, just do it! ;-)