how do I copy the contents of a file into virtual memory?

2.5k views Asked by At

I have a small file, I go over it and count the number of bytes in it:

while(fgetc(myFilePtr) != EOF)
{

   numbdrOfBytes++;

}

Now I allocate virtual memory of the same size:

BYTE* myBuf = (BYTE*)VirtualAlloc(NULL, numbdrOfBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

I now want to copy the content of my file into nyBuf. How do I do it?

Thanks!

3

There are 3 answers

0
AudioBubble On

In outline:

FILE * f = fopen( "myfile", "r" );
fread( myBuf, numberOfBytes, 1, f );

this assumes that the buffer is big enough to hold the contents of the file.

0
Yakov Galka On

Also consider using memory mapped files instead.

0
Martin York On

Try this:

#include <fstream>
#include <sstream>
#include <vector>

int readFile(std::vector<char>& buffer)
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         *
         * Then read the whole file into the buffer.
         */
        buffer.resize(length);
        file.read(&buffer[0],length);
    }
}