Why I can not write sector at position bigger than 0x1FFF? I am trying to write sector in a SD card. The following code work great for sectors number lower than 0x2000 but fail for any sector bigger than 0x1FFFF returning error code number 5. I don't know why? I don't think this is a duplicate question because I can write sectors in the disk but I can't write sector bigger than 0x1FFF. I am using WinHex and Disk Editor to verify that those sector exist.
#include <windows.h>
#include <stdio.h>
int main()
{
LPCWSTR device_name = L"\\\\.\\PHYSICALDRIVE2";
int sector = 0x2000;
//Open the volume
HANDLE hDisk = CreateFile(device_name, (GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDisk != INVALID_HANDLE_VALUE)
{
DWORD ol = 0;
//Lock the volume
if (DeviceIoControl(hDisk, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &ol, NULL))
{
ol = 0;
//Dismount the volume
if (DeviceIoControl(hDisk, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &ol, NULL))
{
unsigned char buff[512];
//Set position at desire sector
int position = sector * 512;
DWORD readBytes = 0;
long moveToHigh = 0;
SetFilePointer(hDisk, position, &moveToHigh, FILE_BEGIN);
//Read the sector
if (ReadFile(hDisk, buff, 512, &readBytes, NULL) && readBytes == 512)
{
//Set the write position
DWORD writenBytes = 0;
moveToHigh = 0;
SetFilePointer(hDisk, position, &moveToHigh, FILE_BEGIN);
if (WriteFile(hDisk, buff, 512, &writenBytes, NULL) && writenBytes == 512)
{
printf("OK for Sector %d \r\n", sector);
}
else
{
DWORD dwError = GetLastError();
printf("Error Code: %d \r\n", dwError);
}
}
}
}
CloseHandle(hDisk);
}
}