【问题标题】:Read specific sector on hard drive using C language on windows在 Windows 上使用 C 语言读取硬盘上的特定扇区
【发布时间】:2015-05-26 23:59:05
【问题描述】:

我已经尝试过这段代码,当我从 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;}

【问题讨论】:

  • 它是哪个窗口?也许这只是权限问题。
  • U盘是FAT32还是NTFS?
  • @EugeneSh。在 Windows 8.1 上
  • @JoseManuelAbarcaRodríguez USB 使用 fat32
  • 别荒谬了,@JoseManuelAbarcaRodríguez。与操作系统相关的多个程序访问硬盘,包括应特权用户的要求,显然这是可能的。可能存在权限问题,但这与“您无能为力”相去甚远。

标签: c windows operating-system boot


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 1970-01-01
    • 2013-07-15
    • 2015-06-17
    • 1970-01-01
    • 2013-03-18
    • 2020-06-12
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多