如何获得文件的地图视图只有ifstream

How to get map view of file just have only ifstream?

本文关键字:ifstream 视图 地图 何获得 文件      更新时间:2023-10-16

我需要创建文件映射,并为我的ifstream获取文件的映射视图。

HANDLE hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, 
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);  
    DWORD dwFileSize = GetFileSize(hFile, NULL);
    HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, 0);
    if (hFileMap != NULL) 
    {
        BYTE *pData = (BYTE *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, dwFileSize); 
        if (pData != NULL)  
        {
            fillDllInfo(pData, dwFileSize);
            UnmapViewOfFile(pData);         
        }               

我在这里创建文件,等等。但我需要做一些类似的事情

std::ifstream pefile;
pefile.open(this->fileName, std::ios::in | std::ios::binary);
if(!pefile.is_open())   
    return error(erId::Cant_Open_File);
    std::streamoff filesize = pefile.tellg();
    //HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, 0);
    //if (hFileMap != NULL) 
    //{
    //  BYTE *pData = (BYTE *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, dwFileSize); 
    //  if (pData != NULL)  
        //{
            fillDllInfo(pData /* ??? */, filesize );
        //  UnmapViewOfFile(pData);         
        //}     

和我的pefile一起工作!在没有boost或其他任何东西的情况下,我如何在我的pefile上获取pData?谢谢

您可以将所有文件加载到缓冲区中,而不是映射内存中的文件。它的效率要低得多,但它是便携的。

#include <string>
#include <fstream>
#include <cstring> // memcpy
void fillDllInfo (char* buf, size_t size)
{
  // ...
}
char* read_whole_stream (std::ifstream& stream, size_t& size)
{
  std::istreambuf_iterator<char> eos;
  std::string s (std::istreambuf_iterator<char>(stream), eos);
  char* buf = new char[s.size()];
  memcpy(buf, s.c_str(), s.size());
  return buf;
}
int main ()
{
  std::ifstream pefile;
  pefile.open("in", std::ios::in | std::ios::binary);
  if (!pefile.is_open())
    return 1;
  size_t filesize;
  char* pData = read_whole_stream(pefile, filesize);
  fillDllInfo(pData, filesize);
  delete[] pData;
  return 0;
}