I have written a C++ code with Visual Studio 2022 on Windiws 11, which writes a sector into a removable flash device (D:)
#include <windows.h>
#include <iostream>
#include <string>
void writeSector(size_t position, const uint8_t* buffer, DWORD sectorSize)
{
HANDLE hDevice = CreateFileA(
"\\.\D:",
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hDevice == INVALID_HANDLE_VALUE)
{
throw std::runtime_error("Error opening device: " + GetLastError());
}
DWORD bytesWritten;
LARGE_INTEGER li = { 0 };
li.QuadPart = position;
if (!SetFilePointerEx(hDevice, li, NULL, FILE_BEGIN))
{
CloseHandle(hDevice);
throw std::runtime_error("Impossible to set file pointer: " + GetLastError());
}
BOOL bRet = WriteFile(hDevice, buffer, sectorSize, &bytesWritten, NULL);
if (!bRet)
{
std::string msg = "WriteFile returned 0 " + GetLastError();
CloseHandle(hDevice);
throw std::runtime_error(msg.c_str());
}
if (bytesWritten != sectorSize)
{
std::string msg = "Written bytes different than expected: " + std::to_string(bytesWritten) + " " + GetLastError();
CloseHandle(hDevice);
throw std::runtime_error(msg.c_str());
}
CloseHandle(hDevice);
}
int main()
{
uint8_t buffer[512] = {0};
writeSector(0, buffer, 512);
writeSector(1024*512, buffer, 512);
writeSector(10*1024*512, buffer, 512);
}
All the checks contained in the function writeSector() are successful except the last one, where the number of actually written bytes bytesWritten is compared with the expected value sectorSize. In fact, the value of bytesWritten is 0. The GetLastError() returns 0: so theoretically there hasn’t been an error: simply, nothing has been written.
Maybe I am writing at wrong addresses or with invalid size?
The geometry of the device, read by DeviceIoControl(), is: {Cylinders={253689} MediaType=RemovableMedia (11) TracksPerCylinder=255 BytesPerSector = 512}.