Home > Back-end >  Why are these 2 sectors different?
Why are these 2 sectors different?

Time:10-02

i tried to read ntfs partition. main function:

int main(int argc, char** argv)
{
    BYTE sector[512];
    ReadSector(L"\\\\.\\E:", 0, sector);
    PrintBPB(ReadBPB(sector));

    BYTE sector2[512];
    ReadSector(L"\\\\.\\E:", 0, sector2);
    PrintBPB(ReadBPB(sector2));
    
    return 0;
}

ReadSector function:

int ReadSector(LPCWSTR  drive, long readPoint, BYTE sector[Sector_Size])
{
    int retCode = 0;
    DWORD bytesRead;
    HANDLE device = NULL;

    device = CreateFile(drive,    // Drive to open
        GENERIC_READ,           // Access mode
        FILE_SHARE_READ | FILE_SHARE_WRITE,        // Share Mode
        NULL,                   // Security Descriptor
        OPEN_EXISTING,          // How to create
        0,                      // File attributes
        NULL);                  // Handle to template

    if (device == INVALID_HANDLE_VALUE) // Open Error
    {
        printf("CreateFile: %u\n", GetLastError());
        return 1;
    }

    SetFilePointer(device, readPoint, NULL, FILE_BEGIN);//Set a Point to Read

    if (!ReadFile(device, sector, 512, &bytesRead, NULL))
    {
        printf("ReadFile: %u\n", GetLastError());
    }
    else
    {
        printf("Success!\n");
    }
    CloseHandle(device);
}

I think the way I copy those bytes into my BPB bpb is fine.

So what happend? Why they are different? I can figure out that its relate to winapi, readfile, createfile but I still dont understand it :(

sorry for my bad english.

here the result:

CodePudding user response:

The bug is in the code we cannot see: PrintBPB. Apparently it switches to hexadecimal output (for the "Volume serial number") and then fails to switch back to decimal until later.

When the code calls PrintBPB a second time the output mode is still in hexadecimal format, and printing "Bytes per Sector" now displays 200 (0x200 is the same value as 512).

If you need to know whether two chunks of memory hold identical values, just memcmp them. This avoids introducing a bug in a transformation (such as console output).

  • Related