我想使用下面的代码打印引导扇区,但是有错误。
#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();
}
而不是打印引导扇区的十六进制数字,microsoft visual studio打印出“CD”流。错误是什么以及如何解决问题?有人可以帮忙吗?
答案 0 :(得分:1)
首先,以管理员身份启动它
从
中删除空格char *dsk=" \\\\.\\PhysicalDrive0";
必须是
char *dsk="\\\\.\\PhysicalDrive0";
并且,如果您使用char * dsk,请在:
进行修改HDISK =的CreateFile(_dsk,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,0,0);
必须是: CreateFileA(......)
#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 = CreateFileA( _dsk, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
//CreateFile()
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();
}