使用FSCTL_LOCK_VOLUME锁定驱动器

时间:2014-06-02 20:02:46

标签: c++ windows winapi

我无法锁定我的C盘,因此我可以稍后提取一些文件信息。

#define wszDrive L"\\\\.\\PhysicalDrive0"
HANDLE targetVol = INVALID_HANDLE_VALUE;
DWORD stats;
targetVol = CreateFile(wszDrive,
        0,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        /*FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS*/0,
        NULL);

    if (targetVol == INVALID_HANDLE_VALUE)    // cannot open the drive
    {
        cout << "error in ioControl with volume handler" << endl;
        system("pause");
    }

    if (DeviceIoControl(targetVol,
        FSCTL_LOCK_VOLUME,
        NULL, 0, NULL, 0,
        &stats,
        NULL) ==0)
    {
        cout << "Error with targetVol DeviceIo" << endl;
        ErrorExit(TEXT("GetProcessId"));
        system("pause");
    }

下面的错误退出会返回“GetProcessID faile with error 1:Incorrect function。”

void ErrorExit(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf,
        0, NULL);

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    ExitProcess(dw);
}

你们是否知道出现了什么问题?

1 个答案:

答案 0 :(得分:4)

FSCTL_LOCK_VOLUME的MSDN文档直接说了

  

如果卷未使用,则锁定该卷

C:驱动器几乎始终正在使用中。它没有被使用的唯一时间是你从不同的媒体启动。