drk
drk

Reputation: 29

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!

Upvotes: 1

Views: 725

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126807

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.

Upvotes: 2

Michaël Roy
Michaël Roy

Reputation: 6471

Well, it depends..

  • if you want what's in your buffer to represent an entire sector of the device, and map it using a struct* or byte offsets - that's usually how it's done. then your offsets sent to SetFilePointer should be aligned on the sector size, then read sector sized buffers. So SetFilePointer(0) -> ReadFile(512 bytes)

  • If you don't care, and just want bytes 12-16, SetFilePointer(12) -> Read(4bytes).

I'd go for solution 1, because it would probably make the code easier to read and maintain in the long run.

Upvotes: 1

Related Questions