Click here to Skip to main content
14,364,319 members
Rate this:
Please Sign up or sign in to vote.
See more:
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?

What I have tried:

#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);
    }   
}
Posted
Updated 8-Nov-19 3:52am
Comments
Richard MacCutchan 7-Nov-19 4:19am
   
You should check the return value from the call to SetFilePointer to see whether that succeeded.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Check the partition layout using DISKPART. Windows typically does not allow you to access a partition using the physical drive because reading it would bypass file security, and writing could corrupt the partition.
You may be able to bypass this if your program is run with elevated privilege.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100