Search code examples
cwindowsmemory-mapped-filesmemory-mapping

How to read bin file (FAT16 partition) from a Memory Mapped File in C?


I have a very small FAT16 partition in a .bin file. I have mapped it into memory using: CreateFile, CreateFileMapping and MapViewOfFile.

What I want to do is to read a specific byte of the file.

For example I want to read offset from 0x36 to 0x3A to check if this is a FAT16 partition:

enter image description here

This is my code until:

#include <Windows.h>
#include <stdio.h>

void CheckError (BOOL condition, LPCSTR message, UINT retcode);


int main(int argc, char *argv[])
{
    HANDLE hFile;
    HANDLE hMap;
    char *pView;
    DWORD TamArchivoLow, TamArchivoHigh;

    //> open file
    hFile =CreateFile (L"disk10mb.bin", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    CheckError(hFile == INVALID_HANDLE_VALUE,"ERROR opening the file", 1);

    //> get file size.
    TamArchivoLow = GetFileSize (hFile, &TamArchivoHigh);


    //> Create the map
    hMap = CreateFileMapping (hFile, NULL, PAGE_READWRITE, TamArchivoHigh, TamArchivoLow, NULL);
    CheckError(NULL== hMap, "ERROR executing CreateFileMapping", 1);

    //> Create the view
    pView= (char *) MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0,  TamArchivoLow);
    CheckError(NULL==pView, "ERROR executing MapViewOfFile", 1);


    // Access the file through pView
    //////////////////////////////////////





    //////////////////////////////////////



    //>Free view and map
    UnmapViewOfFile(pView);
    CloseHandle(hMap);
    CloseHandle(hFile);

    return 0;

}


void CheckError (BOOL condition, LPCSTR message, UINT retcode)
{
    if (condition)
    {
        printf ("%s\n", message);
        ExitProcess (retcode);
    }
}

Solution

  • pview[0x36] will give you the byte at offset 0x36, and so on. To check for the FAT16 signature you could, for instance:

    if (pview[0x36] == 'F' && pview[0x37] == 'A' && pview[0x38] == 'T' &&
            pview[0x39] == '1' && pview[0x3A] == '6') {
        // ...
    }