Click here to Skip to main content
15,893,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 2: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

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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900