0
我想使用下面的代碼打印引導扇區,但有錯誤。直接訪問硬盤
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
short ReadSect
(const char * _dsk, // disk to access
char *&_buff, // buffer where sector will be stored
unsigned int _nsect // sector number, starting with 0
)
{
DWORD dwRead;
HANDLE
hDisk=CreateFile(_dsk,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,0,0);
if(hDisk==INVALID_HANDLE_VALUE) // this may happen if another program is
already reading from disk
{
CloseHandle(hDisk);
return 1;
}
SetFilePointer(hDisk,_nsect*512,0,FILE_BEGIN); // which sector to read
ReadFile(hDisk,_buff,512,&dwRead,0); // read sector
CloseHandle(hDisk);
return 0;
}
int main()
{
char * drv="\\\\.\\C:";
char *dsk=" \\\\.\\PhysicalDrive0";
int sector=0;
int b = 1;
char *buff=new char[512];
ReadSect(dsk,buff,sector);
if((unsigned char)buff[510]==0x55 && (unsigned char)buff[511]==0xaa) cout
<<"Disk is bootable!"<<endl;
else printf("%02hhX\n",(unsigned int)(unsigned char)buff[511]);
printf("\n");
while (b<513)
{
if (b%16==0)
printf(" %02hhX\n",(unsigned int)(unsigned char)buff[b-1]);
else
printf (" %02hhX ",(unsigned int)(unsigned char)buff[b-1]);
b++;
}
getchar();
}
微軟視覺工作室不是打印引導扇區的十六進制數字,而是打印出「CD」流。什麼是錯誤以及如何解決這個問題?誰能幫忙?
您應該檢查是否所有的函數調用成功。例如,'ReadFile'可能會失敗,在這種情況下'buf'只是未初始化的內存([MSVC初始化爲0xCDCDCDCD ...或其他調試版本的值](https://stackoverflow.com/questions/370195 /時,和爲什麼,意志的-OS-初始化內存到0XCD-0xdd-等-上自由的新的malloc - ))。 – Cornstalks
我在ReadFile中檢查_buff的值,並在MSVC中使用調試器在ReadSect中緩衝,並顯示未知符號流。在將其轉換爲十六進制值後,它將CDCDCDCD ...顯示爲輸出,這意味着ReadFile或ReadSect不起作用... – Nimportequi
這不是我確保所有函數調用都成功的意思。例如,['ReadFile'返回'BOOL',其中'TRUE'表示成功,'FALSE'表示失敗](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v = vs.85)的.aspx)。您應該檢查所有函數調用的狀態,以查看它們是否返回任何錯誤。 – Cornstalks