2011-04-25 155 views
3

我有一个小文件,我走了过来,并计算字节数在它:如何将文件的内容复制到虚拟内存中?

while(fgetc(myFilePtr) != EOF) 
{ 

    numbdrOfBytes++; 

} 

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

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

我现在想复制我的文件内容转换成nyBuf。我该怎么做?

谢谢!

+0

在Linux中,有一个很好的系统调用名为'mmap'会为你做到这一点,而不必专门分配内存。有可能Windows有类似的东西。 – Omnifarious 2011-04-25 12:30:57

+1

以获得文件大小,您可以:'fseek(fp,0L,SEEK_END);长尺码= ftell(fp);倒带(fp);' – iCoder 2011-04-25 12:32:08

回答

3

在大纲:

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

这个假定缓冲区足够大,以容纳该文件的内容。

+0

很酷,谢谢 – 2011-04-25 12:18:18

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); 
    } 
} 
相关问题