fedgdsfgdfgdfs
fedgdsfgdfgdfs

Reputation: 31

ReadFile not reading the bytes correctly

I am trying to read a file using readfile, store it into a wide array, then write it into another file. Problem is, when I put them side by side in HxD some bytes are correct (the text, for example) but everything else is completely different. I can't run it either

struct a
{
    BYTE* buff;
    long siz;
};

int main()
{
    HANDLE hFile;
    a struct_a;

    if (hFile = CreateFileW(L"C:\\Windows\\System32\\notepad.exe", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr))
    {
        long lFileSize = GetFileSize(hFile, nullptr);

        if (lFileSize)
        {
            struct_a.siz = lFileSize;
            struct_a.buff = new BYTE[struct_a.siz];

            if (ReadFile(hFile, struct_a.buff, struct_a.siz,
                nullptr, nullptr))
            {
                CloseHandle(hFile);
            }

        }
    }

    HANDLE h = CreateFileA("C:\\Users\\USER\\Desktop\\notepad_new.exe", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr,
        CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);

    WriteFile(h, struct_a.buff, struct_a.siz, nullptr, nullptr);

return 0;
}

I want it to be able to read the file correctly and then write it and have me be able to run it.


As a bonus, I also tried writing some bytes around the end of the file after I read it by doing

struct_a.buff[struct_a.siz - 5] = L'A';

but it never did show up anywhere. But when I tried writing it at the beginning (removing the brackets) it wrote it fine.

EDIT: I tried reading it afterwards and it read the correct letter weirdly enough

EDIT 2: Picture of issue: enter image description here

Upvotes: 0

Views: 425

Answers (1)

The left file in the screenshot is a 32-bit EXE file. The byte you have highlighted that is different is the address of the IMAGE_NT_HEADERS structure in the file.

At address 0xFC, 4 bytes into this structure, the 2 bytes are 4C 01. This is the Machine field in IMAGE_FILE_HEADERS and this value indicates the machine is "i386" (i.e. a 32-bit program).

In the right file, the address is 0xEC instead, and the bytes are 64 86, which is "AMD64" (i.e. this is a 64-bit program).

Probably your program is a 32-bit program, and so it accesses the 32-bit version of System32, because of a Windows feature called file system redirection (thanks to Paul Sanders for the link). On 64-bit Windows, 32-bit programs have System32 redirected to a different folder (which is really called SysWOW64) - according to this table:

                   32-bit System32        64-bit System32

32-bit program   C:\Windows\System32    C:\Windows\sysnative
64-bit program   C:\Windows\SysWOW64    C:\Windows\System32

You can solve this problem by either reading the notepad.exe from sysnative, or comparing it against the one in SysWOW64 instead of the one in System32, or by compiling your program as 64-bit.

Upvotes: 4

Related Questions