0

I want to directly read and write on hard disk partitions. I'm using C by accessing the test partition G: (2GB) for this purpose. I have successfully read the bytes sector wise. I want to read the bytes from sector 1 and writem them to sector 3908880 but i'm not able to write on the disk. Interestingly the WriteFile() method executes successfully but when i use WinHex Editor to view the bytes. It does not show up.

I have seen some similar questions which described the privilege problems but i don't have a privilege problem the function executes successfully but does not write the bytes.

Here is my code:

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();
}
U. Ahmad
  • 76
  • 1
  • 11
  • Writes can be buffered. Your code isn't forcing the cached data to be written to the disk, so there's no guarantee that you'll see it immediately. – Cody Gray - on strike Sep 04 '16 at 14:56
  • 2
    Your code is broken for another reason, though. Assuming that the drive you're writing to is mounted and has a file system, writing directly to the volume risks corruption. You have to first ensure that you have obtained exclusive access to the volume. I can't see anywhere where you are obtaining exclusive access. The documentation for `WriteFile` calls this out in the (lengthy) "Remarks" section. – Cody Gray - on strike Sep 04 '16 at 15:01
  • 2
    Look at your code and ask yourself how is Windows supposed to know that you want to write to sector 3908880. – Ross Ridge Sep 04 '16 at 15:54
  • 1
    You're not actually using `sectorNo` in the write call. – Jonathan Potter Sep 04 '16 at 16:12
  • You might want to read this stackoverflow question and the answer: `http://stackoverflow.com/questions/29219674/read-specific-sector-on-hard-drive-using-c-language-on-windows` – user3629249 Sep 05 '16 at 22:30

0 Answers0