#include "stdafx.h"
#include
#include "stdafx.h"
#include "types_def.h"
#include "compat_error.h"
#include "compat_sem.h"
#include
#include
extern void HexDump(char *buf, int len, int addr);
#define READ 0
#define WRITE 1
//通过给定磁盘的编号,获取到磁盘的句柄
HANDLE GetDiskHandle( int iDiskNo, int op_mode )
{
char szDriverBuffer[128];
memset( szDriverBuffer, 0, 128 );
//格式化设备文件名称
sprintf_s( szDriverBuffer, "\\\\.\\PhysicalDrive%d", iDiskNo );
HANDLE m_hDevice = NULL;
//CreateFile获取到设备句柄
if( op_mode == READ ){
m_hDevice = CreateFileA( szDriverBuffer, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, NULL, NULL );
}else if( op_mode == WRITE ){
m_hDevice = CreateFileA( szDriverBuffer, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, NULL, NULL );
}
//szDriverBuffer --> 设备名称,这里指第一块硬盘,多个硬盘的自己修改就好了
//GENERIC_READ
--> 指定读访问方式
//GENERIC_WRITE --> 指定写访问方式
//FILE_SHARE_READ | FILE_SHARE_WRITE --> 共享模式为读|写,0表示不能共享
//NULL --> NULL表示该句柄不能被子程序继承
//OPEN_EXISTING --> 打开已经存在的文件,文件不存在则函数调用失败
//NULL --> 指定文件属性
//NULL
if( m_hDevice == INVALID_HANDLE_VALUE ){
m_hDevice = NULL;
//无效
return INVALID_HANDLE_VALUE;
}
//设备句柄
return m_hDevice;
}
//通过磁盘的句柄,给定读取的位置,获取到扇区512字节数据返回
//readpos:扇区的逻辑地址
//lpOutBuffer512:用于返回读取的数据
BOOL ReadSectorData( HANDLE& hDevice, UINT64 readpos, __out char *lpOutBuffer512 )
{
LARGE_INTEGER li;
DWORD DCount;
BOOL bResult;
memset( lpOutBuffer512, 0, 512 );
li.QuadPart = readpos*0x200;
//0x200 = 512,求出扇区的字节地址,通过设置读取的地址和长度进行read
SetFilePointer( hDevice, li.LowPart, &li.HighPart, FILE_BEGIN );
DCount = 0;
//计数
bResult = ReadFile( hDevice, lpOutBuffer512, 512, &DCount, NULL );
HexDump(&lpOutBuffer512[0], 512, 0);
return bResult;
}
//通过磁盘的句柄,给定写入数据的位置,写入512字节数据到指定扇区
//writepos:写入扇区的逻辑地址
//lpInBuffer512:准备写入的数据buff
BOOL WriteSectorData( HANDLE& hDevice, UINT64 writepos, __in char *lpInBuffer512 )
{
LARGE_INTEGER li;
DWORD DCount;
BOOL bResult;
li.QuadPart = writepos * 0x200;
//0x200 = 512,求出扇区的字节地址,通过设置写入的地址和长度进行write
SetFilePointer( hDevice, li.LowPart, &li.HighPart, FILE_BEGIN );
DCount = 0;
//计数
bResult = WriteFile( hDevice, lpInBuffer512, 512, &DCount, NULL );
return bResult;
}
int mytestudisk_main( void )
{
char *lpInOutBuffer512;
HANDLE m_hDevice = NULL;
TRACE( "in mytestudisk_main\r\n" );
lpInOutBuffer512 = (char *)malloc(512+1);
m_hDevice = GetDiskHandle( 1, READ );
ReadSectorData( m_hDevice, 14, lpInOutBuffer512 );
CloseHandle(m_hDevice);
HexDump( &lpInOutBuffer512[0],512, 0);
m_hDevice = GetDiskHandle( 1, WRITE );
lpInOutBuffer512[0] = 0x5a;
HexDump(&lpInOutBuffer512[0], 512, 0);
WriteSectorData(m_hDevice, 14, &lpInOutBuffer512[0]);
CloseHandle(m_hDevice);
free(lpInOutBuffer512);
lpInOutBuffer512 = NULL;
return 0;
}