首页 > 解决方案 > WINAPI:无法从主磁盘读取 (PhysicalDrive0)

问题描述

已解决:请参阅下面的评论。应读取 512(或磁盘扇区大小)字节的倍数。

我正在尝试从我的主驱动器读取数据(此驱动器是 SSD 驱动器,操作系统存储在此驱动器中),但该功能一直失败并读取 0 字节。我以管理员身份运行该程序。

这是我的代码:

int main() {
    char a[100];

    HANDLE hMainDisk = CreateFile("\\\\.\\PhysicalDrive0", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hMainDisk == INVALID_HANDLE_VALUE) {
        std::cout << "ERROR: Main disk could not be found.\n"; //This is not printed.
    }

    unsigned char data[1000];
    BOOL succeeded = ReadFile(hMainDisk, bootloaderData, 1000, &numBytesRead, 0);
    DWORD error = GetLastError();
    CloseHandle(hMainDisk);
    if (numBytesRead != 1000) {
        std::cout << "ERROR: Less than 1,000 bytes were read. Only " << numBytesRead << " bytes were read\n"; //This is printed.
    }
    if (succeeded == FALSE) {
        std::cout << "ERROR: Main disk read failed.\n"; //This is also printed
    }
    if (error == ERROR_INVALID_USER_BUFFER || error ==     ERROR_NOT_ENOUGH_MEMORY) {
        std::cout << "ERROR: Too many IO requests.\n"; //This is not printed
    }

    std::cin >> a;
    return 0;
 }

标签: c++winapihard-drive

解决方案


推荐阅读