如何将文件内容复制到虚拟内存中?

时间:2011-04-25 12:08:08

标签: c++ windows operating-system virtualalloc

我有一个小文件,我查看它并计算其中的字节数:

while(fgetc(myFilePtr) != EOF)
{

   numbdrOfBytes++;

}

现在我分配相同大小的虚拟内存:

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

我现在想将我的文件内容复制到nyBuf中。我该怎么做?

谢谢!

3 个答案:

答案 0 :(得分:3)

概述:

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

这假设缓冲区足够大以容纳文件的内容。

答案 1 :(得分:3)

另请考虑使用memory mapped files

答案 2 :(得分:2)

试试这个:

#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);
    }
}