Search code examples
c++windowsreadfile

C++ sector aligned read


Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.

Lets assume whe are in a Windows machined, and we are using the ReadFile() C function to read x bytes from a device.

I know we can only read sector aligned data, but recently i discovered the SetFilePointer() function, that allow us to put a pointer in x bytes of the device we have previously opened with CreateFile().

My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

SetFilePointer(device, 12, NULL, FILE_BEGIN);

(device is a HANDLE to an existing device,for the sake of this example lets assume its a USB pen drive), in that example we set a pointer thatis pointing to the 12th byte starting from FILE_BEGIN.

If i were to read the equivalent of one sector (512 bytes) starting from that 12th byte, would i need to make my read fucntion like this:

ReadFile(device, sector, (512 - 12), &bytesRead, NULL)

or like this:

ReadFile(device, sector, 512, &bytesRead, NULL)

Regardless, thanks!


Solution

  • My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

    SetFilePointer(device, 12, NULL, FILE_BEGIN);
    

    ... then you are no longer reading sector-aligned data, and you'll get error 87 in the ReadFile call. Reading sector-aligned data doesn't just mean that you have to read in sector-sized blocks, but you must always read blocks that start on sector boundaries.

    You have to seek to the sector containing the bytes of your interest (so, position/sector_size*sector_size), read the whole sector and extract the bytes of your interest from the data you read.