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

3

5

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!

Fons answered 25/4, 2011 at 12:8 Comment(2)
On Linux, there is a nice system call called mmap that will do this for you without having to specifically allocate memory. It's possible Windows has something similar.Gav
to get the file size, your can: fseek(fp, 0L, SEEK_END); long size = ftell(fp); rewind(fp);Kiowa
H
3

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.

Hallerson answered 25/4, 2011 at 12:13 Comment(0)
H
3

Also consider using memory mapped files instead.

Horseshoes answered 25/4, 2011 at 12:32 Comment(0)
C
2

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);
    }
}
Carbamidine answered 25/4, 2011 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.