Friends who know real mode programming know that you can use the INT 13 interrupt of the BIOS to perform absolute reading and writing of the disk, but in the NT environment, you cannot use the INT 13 interrupt to directly read and write the hard disk. Here, we can use CreateFile and Set the path name to "//./X:" to open the logical disk and perform reading and writing. X is the drive letter.
The CreateFile function prototype is as follows:
HANDLE CreateFile(LPCTSTR lpFileName, DWord dwDesiredaccess, DWORD dwShareMode,LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDistribution, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);
lpFileName: The name of the file to be opened
dwDesiredAccess: If it is GENERIC_READ, it means that read access to the device is allowed; if it is GENERIC_WRITE, it means that write access to the device is allowed (can be used in combination); if it is zero, it means that only information related to one device is allowed to be obtained.
dwShareMode: Zero means no sharing; FILE_SHARE_READ and/or FILE_SHARE_WRITE means shared access to the file is allowed
lpSecurityAttributes: Pointer to a SECURITY_ATTRIBUTES structure that defines the security attributes of the file
dwCreationDistribution: Creation method
dwFlagsAndAttributes: Other attributes
hTemplateFile: If non-zero, specifies a file handle. The new file will copy the extended attributes from this file
The following example is compiled and passed under Windows xp. The function it implements is to read the boot sector of the C drive and display the read data.
PRogram ReadDisk;
uses
SysUtils,
Windows;
var
Buf: array [0..511] of Byte; //data buffer
ShowText, TmpStr: string;
FileHandle: THandle;
ReadCount, i: Cardinal;
begin
//Open disk
FileHandle := CreateFile('//./C:', GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0);
if FileHandle = INVALID_HANDLE_VALUE then
begin
MessageBox(GetDesktopWindow, 'Failed to open disk', 'ERROR', MB_OK);
ExitProcess(0);
end;
//Read boot sector data
if ReadFile(FileHandle, Buf, 512, ReadCount, nil) then
begin
SetLength(ShowText, Length(Buf) * 3);
//Convert data to string
for i := Low(Buf) to High(Buf) do
begin
TmpStr := Format('%2.2x ', [Buf[i]]);
CopyMemory(@ShowText[i*3+1], @TmpStr[1], 3);
end;
end;
MessageBox(GetDesktopWindow, PChar(ShowText), 'Boot Sector', MB_OK);
CloseHandle(FileHandle);
ExitProcess(0);
end.