[在Windows上使用C语言读取硬盘上的特定扇区

问题描述 投票:1回答:2

我已经尝试过此代码,当我从USB闪存驱动器中读取扇区时它可以工作,但不适用于硬盘驱动器上的任何分区,因此当您尝试从USB或USB中读取数据时,我想知道是否相同?从硬盘驱动器

int ReadSector(int numSector,BYTE* buf){

int retCode = 0;
BYTE sector[512];
DWORD bytesRead;
HANDLE device = NULL;

device = CreateFile("\\\\.\\H:",    // Drive to open
                    GENERIC_READ,           // Access mode
                    FILE_SHARE_READ,        // Share Mode
                    NULL,                   // Security Descriptor
                    OPEN_EXISTING,          // How to create
                    0,                      // File attributes
                    NULL);                  // Handle to template

if(device != NULL)
{
    SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;

    if (!ReadFile(device, sector, 512, &bytesRead, NULL))
    {
        printf("Error in reading disk\n");
    }
    else
    {
        // Copy boot sector into buffer and set retCode
        memcpy(buf,sector, 512);
        retCode=1;
    }

    CloseHandle(device);
    // Close the handle
}

return retCode;}
c windows operating-system boot
2个回答
2
投票

问题是共享模式。您已指定FILE_SHARE_READ,这意味着不允许其他人对该设备进行写操作,但是该分区已经以读/写方式挂载,因此无法为您提供该共享模式。如果使用FILE_SHARE_READ|FILE_SHARE_WRITE,它将起作用。 (很好,只要磁盘扇区大小为512字节,并且该进程正在以管理员权限运行。)

您还在错误地检查故障;如果失败,CreateFile返回INVALID_HANDLE_VALUE,而不是NULL

我已成功测试此代码:

#include <windows.h>

#include <stdio.h>

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.