2

please help me with reading memory mapped file. I open file in code below. And then i want to read bytes from 8 to 16. How can i do that?

// 0. Handle or create and handle file
m_hFile = CreateFile(file_path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_hFile == INVALID_HANDLE_VALUE)
{
    if (GetLastError() == ERROR_FILE_NOT_FOUND)
    {
        m_hFile = createNewFile(file_path.c_str());
    }
    else throw GetLastError();
}

// 1. Create a file mapping object for the file
m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (m_hMapFile == NULL) throw GetLastError();

// 2. Map the view.
m_lpMapAddress = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
// to map
if (m_lpMapAddress == NULL) throw GetLastError();
ExiD
  • 87
  • 2
  • 12
  • 1
    Is a dublicate from this one: [link](http://stackoverflow.com/questions/9889557/mapping-large-files-using-mapviewoffile). You have the pointer m_lpMapAddress, which is hopefully a byte pointer. Add 8 bytes to the pointer and read the memory. That's all – mrAtari Aug 03 '16 at 09:36
  • @mrAtari How can i add 8 bytes? – ExiD Aug 03 '16 at 09:37
  • m_lpMapAddress +=8 – mrAtari Aug 03 '16 at 10:50
  • @mrAtari: That won't work. `MapViewOfFile` returns `void*`. If the assignment to `m_lpMapAddress` works without a cast, then its type must be `void*` as well. You cannot use `operator+=` on a `void*`. You'll have to cast to a specific type (`unsigned char` for bytes) first. – IInspectable Aug 03 '16 at 10:56
  • Have you ever heard about pointer casting? char* cursor = (char*)m_lpMapAddress; cursor+=8; – mrAtari Aug 03 '16 at 10:59
  • @mrAtari: Given the fact, that I suggested you cast the `void*` to a specific type, it seems plausible, that I *"have [...] heard about [...] casting"*. What point are you trying to make? – IInspectable Aug 03 '16 at 11:05

1 Answers1

6

You can access it like any other memory block. Here's an example that prints those bytes interpreted as unsigned chars:

unsigned char *mappedDataAsUChars = (unsigned char*)m_lpMapAddress;

for(int k = 8; k < 16; k++)
    std::cout << "Byte at " << k << " is " << mappedDataAsUChars[k] << std::endl;
user253751
  • 57,427
  • 7
  • 48
  • 90