Read specific sector on hard drive using C language on windows

前端 未结 1 469
萌比男神i
萌比男神i 2021-01-03 15:54

i have tried this code it works when i read a sector from an USB flash drive but it does\'nt work with any partiton on hard drive , so i want to know if it\'s the same thing

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 17:00

    The problem is the sharing mode. You have specified FILE_SHARE_READ which means that nobody else is allowed to write to the device, but the partition is already mounted read/write so it isn't possible to give you that sharing mode. If you use FILE_SHARE_READ|FILE_SHARE_WRITE it will work. (Well, provided the disk sector size is 512 bytes, and provided the process is running with administrator privilege.)

    You're also checking for failure incorrectly; CreateFile returns INVALID_HANDLE_VALUE on failure rather than NULL.

    I tested this code successfully:

    #include 
    
    #include 
    
    int main(int argc, char ** argv)
    {
        int retCode = 0;
        BYTE sector[512];
        DWORD bytesRead;
        HANDLE device = NULL;
        int numSector = 5;
    
        device = CreateFile(L"\\\\.\\C:",    // Drive 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
    
        if(device == INVALID_HANDLE_VALUE)
        {
            printf("CreateFile: %u\n", GetLastError());
            return 1;
        }
    
        SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;
    
        if (!ReadFile(device, sector, 512, &bytesRead, NULL))
        {
            printf("ReadFile: %u\n", GetLastError());
        }
        else
        {
            printf("Success!\n");
        }
    
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题