c++ - 使用 DeviceIoControl 函数读取 MBR 时出现问题

标签 c++ winapi

我在调用 DeviceIoControl 函数读取可移动设备的 MBR 时出错。错误代码为 5。这意味着访问被拒绝!我使用的是 windows xp sp2。

#include "stdafx.h"
#include  <windows.h>
#include <winioctl.h>
#include <stdio.h>

 BOOL GetMBR(PARTITION_INFORMATION *pdg)
 {

    HANDLE hDevice;               // handle to the drive to be examined
    BOOL bResult;                 // results flag
    DWORD junk;                   // discard results

    hDevice = CreateFile(TEXT("\\\\.\\G:"),     // drive to open
                    0,                          // no access to the drive
                    FILE_SHARE_READ |           // share mode
                    FILE_SHARE_WRITE,
                    NULL,                       // default security attributes
                    OPEN_EXISTING,              // disposition
                    0,                          // file attributes
                    NULL                        // do not copy file attributes  
              );            

  if (hDevice == INVALID_HANDLE_VALUE)          // cannot open the drive
  {
        printf("CreateFile() failed!\n");
        return (FALSE);
  }

  bResult = DeviceIoControl(
                hDevice,                        // device to be queried
                IOCTL_DISK_GET_PARTITION_INFO,  // operation to perform
                NULL, 0,                        // no input buffer
                pdg, sizeof(*pdg),              // output buffer
                &junk,                          // # bytes returned
                (LPOVERLAPPED) NULL             // synchronous I/O
            );  

  CloseHandle(hDevice);
  return (bResult);

}


int _tmain(int argc, _TCHAR* argv[])
{
    PARTITION_INFORMATION pdg;              // disk drive geometry structure
    BOOL bResult;                   // generic results flag
    ULONGLONG DiskSize;             // size of the drive, in bytes

    bResult = GetMBR(&pdg);

    if (bResult)
    {

    }

    else
    {
        printf ("GetDriveGeometry() failed. Error %ld.\n", GetLastError ());
    }

    getchar();

    return ((int)bResult);
}

最佳答案

使用 FILE_READ_ATTRIBUTES 打开它。

关于c++ - 使用 DeviceIoControl 函数读取 MBR 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3362037/

相关文章:

c++ - 如何使用指定的 gcc 编译 Armadillo 库?

C++多维数组初始化

Python,为什么返回的 win32api.ShellExecute 句柄不适用于 win32gui.GetWindowRect

windows - 如何计算每个 TCP 连接(系统范围)发送和接收的字节数?

c - 在WM_RBUTTONUP中,MK_RBUTTON真的意味着SHIFT键按下了吗?什么?

c++ - 指向对象及其析构函数的指针

python - CMake 不链接 Python

c++ - 从源代码生成类图

winapi - Win32 : Determine whether stdout handle is char or wchar stream

c - 函数中返回文件/文件夹结构的指针