Code:
#pragma comment( lib, "user32.lib" )
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <winioctl.h>
int ReadSectors(DISK_GEOMETRY dg, HANDLE hDrive, DWORD dwCylinder, DWORD dwTrack, DWORD dwSector, DWORD dwNumberOfSectors)
{
DWORD dwCylinders, dwTracksPerCylinder, dwSectorsPerTrack, dwBytesPerSector;
DWORD dwReadOffset = 0;
DWORD dwNotUsed;
char *pSectorData = NULL;
dwCylinders = dg.Cylinders.QuadPart;
dwTracksPerCylinder = dg.TracksPerCylinder;
dwSectorsPerTrack = dg.SectorsPerTrack;
dwBytesPerSector = dg.BytesPerSector;
DWORD dwNumberOfBytesToRead = dwBytesPerSector;
printf("Cylinders: %d\nTracks Per Cylinder: %d\nBytes Per Sector: %d\n\n", dwCylinders, dwTracksPerCylinder, dwBytesPerSector);
dwNumberOfBytesToRead *= dwNumberOfSectors;
dwReadOffset = ((dwCylinder * dwTracksPerCylinder + dwTrack) * dwSectorsPerTrack + dwSector) * dwBytesPerSector;
LARGE_INTEGER liOffset = {dwReadOffset};
pSectorData = (char*) malloc(dwNumberOfBytesToRead);
memset(pSectorData, 0, sizeof pSectorData);
if(dwReadOffset != 0)
{
if(!SetFilePointer(hDrive, (liOffset.LowPart), &liOffset.HighPart, FILE_BEGIN))
{
printf("SetFilePointer failed\n");
return -1;
}
}
if(!ReadFile(hDrive, pSectorData, dwNumberOfBytesToRead, &dwNotUsed, NULL))
{
printf("readfile failed\n");
return -2;
}
for(int iIndex = 0; iIndex <= dwNumberOfBytesToRead; iIndex++)
printf("%02x", pSectorData[iIndex]);
return 0;
}
int main(void)
{
int iDiskInputID = 0;
char cDriveLetter = 'c';
DISK_GEOMETRY dg;
DWORD dwNotUsed;
char cPhysicalDisk[24];
ZeroMemory(cPhysicalDisk, 24);
wsprintf(cPhysicalDisk, "\\\\.\\PhysicalDrive%d", iDiskInputID);
HANDLE hDrive = CreateFile(cPhysicalDisk, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (!DeviceIoControl(hDrive, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &dg, sizeof(dg), &dwNotUsed, (LPOVERLAPPED)NULL))
{
printf("Deviceiocontrol failed\n");
return -3;
}
CloseHandle(hDrive);
ZeroMemory(cPhysicalDisk, 24);
wsprintf(cPhysicalDisk, "\\\\.\\%c:", cDriveLetter);
hDrive = CreateFile(cPhysicalDisk, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
return ReadSectors(dg, hDrive, 0 ,0 ,1 ,1);
}