C++ 扇区对齐读取 [英] C++ sector aligned read
问题描述
我问这个是因为我在读取原始设备时无法理解扇区对齐读取.
Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.
假设在 Windows 机器中,我们使用 ReadFile()
C 函数从设备读取 x 个字节.
Lets assume whe are in a Windows machined, and we are using the ReadFile()
C function to read x bytes from a device.
我知道我们只能读取扇区对齐的数据,但最近我发现了 SetFilePointer()
函数,它允许我们将指针放在我们之前用 CreateFile()
.
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()
.
我的问题是,如果我们需要读取扇区对齐的数据,如果我们使用 SetFilePointer()
例如像这样:
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);
(设备是现有设备的 HANDLE
,为了这个例子,我们假设它是一个 USB 笔式驱动器),在那个例子中,我们设置了一个指向第 12 个字节的指针,从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
.
如果我要从第 12 个字节开始读取相当于一个扇区(512 个字节)的内容,我是否需要像这样设置读取功能:
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)
或者像这样:
ReadFile(device, sector, 512, &bytesRead, NULL)
不管怎样,谢谢!
推荐答案
我的问题是,如果我们需要读取扇区对齐的数据,如果我们使用
SetFilePointer()
例如像这样:
SetFilePointer(device, 12, NULL, FILE_BEGIN);
... 那么您将不再读取扇区对齐的数据,并且您将在 ReadFile
调用中收到错误 87.读取扇区对齐的数据不仅意味着您必须读取扇区大小的块,而且您必须始终读取从扇区边界开始的块.
... 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.
您必须寻找包含您感兴趣的字节的扇区(因此,position/sector_size*sector_size
),读取整个扇区并从您读取的数据中提取您感兴趣的字节.
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.
这篇关于C++ 扇区对齐读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!