I'm trying to write directly to an offset on a disk (I'm running it inside a virtual machine, but nontheless) using the following code:
int main()
{
OVERLAPPED overlapped;
char DataBuffer[] = "AAAAAAA";
HANDLE dHandle = CreateFile(_T("\\\\.\\PhysicalDrive0"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
NULL
);
// LOCK DISK
int err;
DWORD stuff = 0;
if (!DeviceIoControl
(
dHandle,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&stuff,
NULL
))
{
err = GetLastError();
fprintf(stderr, "Error %u locking volume.\n", err);
return err;
}
DWORD lpBytesReturned;
if (!DeviceIoControl(
dHandle, // handle to a volume
(DWORD)FSCTL_DISMOUNT_VOLUME, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
NULL, // lpOutBuffer
0, // nOutBufferSize
&lpBytesReturned, // number of bytes returned
NULL // OVERLAPPED structure
)) {
err = GetLastError();
fprintf(stderr, "Error %u dismount volume.\n", err);
return err;
}
printf("Handle is : %d\n", dHandle);
int set_res = SetFilePointer(dHandle, 791908352, NULL, FILE_BEGIN);
if (set_res == INVALID_SET_FILE_POINTER) {
printf("invalid set_file pointer\n");
printf("Last error was : %d\n", GetLastError());
}
DWORD written = 0;
int res2 = WriteFile(dHandle, DataBuffer, 4096, &written, NULL);
if (!res2) {
printf("Last error was : %d\n", GetLastError());
printf("Written : %d", written);
}
printf("Written : %d", written);
return 0;
When I run the following code I get:
5 (0x5)
Access is denied.
After trying to WriteFile. I've run the program as administrator. I know the offset is valid, because I could read relevant data from that offset.
Any idea why I'm getting it? And how could I make it work?