Я хочу напрямую читать и писать на разделы жесткого диска. Я использую C, обращаясь к тестовому разделу G: (2 ГБ) для этой цели. Я успешно прочитал байты по секторам. Я хочу прочитать байты из сектора 1 и записать их в сектор 3908880, но не могу записать на диск. Интересно, что метод WriteFile() выполняется успешно, но когда я использую редактор WinHex для просмотра байтов. Он не появляется.
Я видел несколько подобных вопросов, в которых описывались проблемы с привилегиями, но у меня нет проблемы с привилегиями, функция выполняется успешно, но не записывает байты.
Вот мой код:
HANDLE getDeviceHandle(wchar_t* partition, char mode)
{
HANDLE device;
int retCode = 1;
if (mode == 'r')
{
device = CreateFile(
partition, // Partition to open
GENERIC_READ, // Access mode
FILE_SHARE_READ | FILE_SHARE_WRITE, // Share Mode
NULL, // Security Descriptor
OPEN_EXISTING, // How to create
0, // File attributes
NULL); // Handle to template
}
else if(mode == 'w')
{
device = CreateFile(
partition, // Partition to open
GENERIC_READ | GENERIC_WRITE, // Access mode
FILE_SHARE_READ | FILE_SHARE_WRITE, // Share Mode
NULL, // Security Descriptor
OPEN_EXISTING, // How to create
0, // File attributes
NULL); // Handle to template
}
if (device == INVALID_HANDLE_VALUE)
retCode = -1;
if(retCode == 1)
return device;
else
return NULL;
}
int WriteSector(HANDLE device ,BYTE* bytesToWrite, DWORD size, int sectorNo )
{
char buffForPrint[512] = { 0 };
int Code = 0;
DWORD byteswritten;
int NoOfSectorsOnPartition = 0;
DWORD bytesReturnedSize = 0;
if (NULL == device)
{
printf("Exiting from WriteSector\n");
return 0;
}
else
{
int ret = getNoOfSectors(device, bytesReturnedSize);
if (-1 != ret)
{
NoOfSectorsOnPartition = ret;
if (sectorNo > NoOfSectorsOnPartition)
{
printf("Selected sector out of range");
Code = -1;
return Code;
}else
{
DWORD status;
if (!DeviceIoControl(device, IOCTL_DISK_IS_WRITABLE, NULL, 0, NULL, 0, &status, NULL))
{
// error handling; not sure if retrying is useful
}else if (!WriteFile(device, bytesToWrite, size, &byteswritten, NULL))
{
printf("Error in writing.Error Code: %i\n", GetLastError());
Code = -1;
return Code;
}
else
{
printf("Sector Written\n");
Code = 1;
}
}
}
}
return Code;
}
int main()
{
static BYTE read[512];
HANDLE hand;
int sector =1;
hand = getDeviceHandle(L"\\\\.\\G:", 'r');
if (ReadSector(hand, read, 512, sector) == 1)
{
printf("successfully read sector %i\n", sector);
}
sector = 3908880;
hand = getDeviceHandle(L"\\\\.\\G:", 'w');
if (WriteSector(hand,read,SECTOR_SIZE,sector) == 1) //SECTOR_SIZE 512
{
printf("successfully wrote sector %i\n",sector);
}
CloseHandle(hand); // Close the handle
getch();
}
WriteFile
упоминает об этом в разделе (длинных) примечаний. - person Cody Gray   schedule 04.09.2016sectorNo
в вызове записи. - person Jonathan Potter   schedule 04.09.2016http://stackoverflow.com/questions/29219674/read-specific-sector-on-hard-drive-using-c-language-on-windows
- person user3629249   schedule 06.09.2016