2011-04-25 2 views
3

, 나는 그 위에 가서 바이트의 수를 계산 :파일 내용을 가상 메모리로 복사하는 방법은 무엇입니까? 나는 작은 파일이

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

내가 지금 복사 할 :

while(fgetc(myFilePtr) != EOF) 
{ 

    numbdrOfBytes++; 

} 

이 지금은 같은 크기의 가상 메모리를 할당 내 파일의 내용을 nyBuf에 저장합니다. 어떻게해야합니까?

감사합니다. 개요에서

+0

리눅스에서 특별히 메모리를 할당하지 않고 당신을 위해 이것을 할 것'mmap'라는 좋은 시스템 호출이 있습니다. Windows에는 비슷한 것이있을 수 있습니다. – Omnifarious

+1

파일 크기를 얻으려면 다음을 할 수 있습니다 :'fseek (fp, 0L, SEEK_END); 긴 크기 = ftell (fp); 되감기 (fp); ' – iCoder

답변

3

는 :

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

이 버퍼는 파일의 내용을 저장하기에 충분히 큰 것으로 가정합니다.

+0

멋지다, 고맙습니다. –

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); 
    } 
} 
관련 문제