2014-10-09 65 views
-2

我對C相當陌生,而且我正試圖編寫一個小應用程序來讀取驅動器的全部原始內容。使用ReadFile讀取整個PhysicalDrive內容

這是我的代碼;

int main(int argc, char *argv[]) { 
    HANDLE hFile; 
    DWORD dwBytesRead; 
    char buff[512]; 

    hFile = CreateFile("\\\\.\\PhysicalDrive2", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); 

    if(hFile == INVALID_HANDLE_VALUE){ 
     printf("%d",GetLastError()); 
     return; 
    } 

    SetFilePointer(hFile, 512*0, NULL, FILE_BEGIN); 
    ReadFile(hFile, buff, 512, &dwBytesRead, NULL); 
    CloseHandle(hFile); 

    return 0; 
} 

如何將ReadFile放入循環以讀取驅動器上的所有數據?我最終需要將緩衝區的內容保存到磁盤。

感謝

+0

看從'ReadFile'的返回值。 「如果函數成功,返回值爲非零(TRUE),如果函數失敗或異步完成,則返回值爲零(FALSE)。要獲得擴展的錯誤信息,請調用GetLastError函數。 – chux 2014-10-09 19:12:28

+0

只有在驅動器上沒有安裝有文件系統的卷時才能執行此操作。在現代版本的Windows上,無法通過「PhysicalDrive」設備訪問由文件系統佔用的塊。即使有管理員權限。 – 2014-10-09 21:37:40

+1

@BenVoigt只是爲了澄清,管理員閱讀任何地方都沒有限制。寫入安裝卷聲明的區域在NT6上被阻止。 – 2014-10-09 22:48:22

回答

1

循環可能是這樣的:

hFile = CreateFile(...); 
if (hFile == INVALID_HANDLE_VALUE) 
{ 
    // handle error 
} 

while (true) 
{ 
    unsigned char buff[32768]; // needs to be a multiple of sector size 
    DWORD dwBytesRead; 
    if (!ReadFile(hFile, buff, sizeof buff, &dwBytesRead, NULL)) 
    { 
     // handle error 
    } 
    if (dwBytesRead == 0) 
    { 
     break; // we reached the end 
    } 
    // do something with the dwBytesRead that were read 
} 

CloseHandle(hFile);