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

3

我尝试过这段代码,它可以从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;}

是哪个窗口?也许只是权限问题。 - undefined
@EugeneSh。在Windows 8.1上。 - undefined
@JoseManuelAbarcaRodríguez USB使用FAT32。 - undefined
@JoseManuelAbarcaRodr铆guez NTFS .. -> @JoseManuelAbarcaRodr铆guez NTFS .. (NTFS鏂囦欢绯荤粺) - undefined
2
别胡说八道,@JoseManuelAbarcaRodríguez。与操作系统相关的多个程序都可以访问硬盘,甚至包括特权用户的要求,所以显然是可以做到的。可能会有权限问题,但这与“无能为力”相去甚远。 - undefined
显示剩余9条评论
1个回答

4
问题在于共享模式。您已指定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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接