Search code examples
c++parsingportable-executable

How to parse EXE file and get data from IMAGE_DOS_HEADER structure using c++ and Window.h?


I am trying to parse PE file in windows and get data from this structure

IMAGE_DOS_HEADER

I wrote this code, that reads bytes from exe file.

 #include <Windows.h>
    
    int main()
    {
        // open the file for binary reading
        std::ifstream file;
            file.open("D:/SomeProgram.exe", ios_base::binary);
    
        if (!file.is_open())
            return 1;
    
        // get the length of the file
        file.seekg(0, ios::end);
        size_t fileSize = file.tellg();
        file.seekg(0, ios::beg);
    
        // create a vector to hold all the bytes in the file
        std::vector<byte> data(fileSize, 0);
    
        // read the file
        file.read(reinterpret_cast<char*>(&data[0]), fileSize);

I have no idea, how to get data, that contains e_magic, e_cbip, e_cp .... and the most important e_ifanew. I know, that this structure IMAGE_DOS_HEADER is stored in Windows.h, but I don't know how to use it to get fields from any exe file.


Solution

  • Declare an instance of the structure and copy the data into it:

    IMAGE_DOS_HEADER idh;
    
    if ( fileSize >= sizeof(idh) )
    {
        std::memcpy(&idh, &data[0], sizeof(idh));
    }