根据GetLastError,直接写入磁盘会导致错误代码5

时间:2018-10-22 01:10:34

标签: c++ windows disk getlasterror

我正在尝试在Windows中直接写入USB磁盘。我使用CreateFile函数创建磁盘句柄,并使用WriteFile函数尝试写入文件。 WriteFile函数失败,状态码为5(根据GetLastError)。我尝试使用FSCTL_DISMOUNT_VOLUME锁定磁盘卷,但是该卷是隐藏的,因此无法获得其卷号。

代码:

    u8 Disk::Init()
    {
        char fn[24] = { 0 };
        sprintf(fn, "\\\\.\\PhysicalDrive%d", (int)m_nDiskNum);
        m_hDisk = CreateFileA(fn, GENERIC_WRITE | GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
            OPEN_EXISTING,
            FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING, 0);

        if (INVALID_HANDLE_VALUE == m_hDisk)
        {
            return (FAIL);
        }

        //m_DiskInfo.Init();
        return Lock();
    }

    u8 Disk::Lock()
    {
        STORAGE_DEVICE_NUMBER d1;
        DWORD nr;
        char dn[8], c;

        if (!DeviceIoControl((HANDLE)m_hDisk, IOCTL_STORAGE_GET_DEVICE_NUMBER,
            NULL, 0, &d1, sizeof(d1), &nr, 0))
        {
            return (FAIL);
        }

        strcpy(dn, "\\\\.\\A:");

        // some volume is hided, so I cannot get its letter
        for (c = 'C'; c < 'Z'; c++)
        {
            HANDLE hd;
            STORAGE_DEVICE_NUMBER d2;

            dn[4] = c;
            hd = CreateFileA(dn, GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                NULL, OPEN_EXISTING, 0, 0);

            if (hd == INVALID_HANDLE_VALUE)
            {
                continue;
            }

            if ((!DeviceIoControl(hd, IOCTL_STORAGE_GET_DEVICE_NUMBER,
                NULL, 0, &d2, sizeof(d2), &nr, 0)) ||
                (d1.DeviceType != d2.DeviceType) ||
                (d1.DeviceNumber != d2.DeviceNumber))
            {
                CloseHandle(hd);
                continue;
            }

            if (!DeviceIoControl(hd, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0,
                &nr, 0))
            {
                CloseHandle(hd);
                return (FAIL);
            }

            m_LockedVolums.push_back(hd);
        }

        return (SUCC);
    }

    u8 Disk::UnLock()
    {
        for (auto it : m_LockedVolums)
        {
            CloseHandle(it);
        }

        m_LockedVolums.clear();
        return (SUCC);
    }

    u8 Disk::WriteSector(_Out_opt_ u8 * cBuf, int nStartSec, int nSecCont/* = 1*/)
    {
        if (Seek(nStartSec))
        {
            return(FAIL);
        }

        unsigned long nWrited;

        if ((!WriteFile((HANDLE)m_hDisk, cBuf, nSecCont * m_nBytePerSec, &nWrited, NULL))
            || (nSecCont * m_nBytePerSec != (int)nWrited))
        {
            return(FAIL);
        }

        return(SUCC);
    }

1 个答案:

答案 0 :(得分:0)

我认为您没有正确锁定音量。

Controller IO控件卸载了文件系统,但我认为它不会锁定它以进行写入。之后使用FSCTL_LOCK_VOLUME(或者,如果该卷没有Windows可读文件系统,因此未安装),则使用enter image description here来请求写访问权限。

P.S。我认为您需要将应用程序提升运行才能使用该API。