【发布时间】:2017-05-27 16:53:36
【问题描述】:
我想用下面的代码打印出引导扇区,但是有错误。
#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”流。错误是什么以及如何解决问题?有人可以帮忙吗?
【问题讨论】:
-
您应该检查所有函数调用是否成功。例如,
ReadFile可能会失败,在这种情况下,buf只是未初始化的内存 (which MSVC initializes to0xCDCDCDCD...or some other value for debug builds)。 -
我使用 MSVC 中的调试器检查了 ReadFile 中 _buff 和 ReadSect 中 buff 的值,它显示了一个未知符号流。将其转换为十六进制值后,显示 CDCDCCDD...作为输出,这意味着 ReadFile 或 ReadSect 不起作用...
-
这不是我要确保所有函数调用成功的意思。例如,
ReadFilereturns aBOOLwhereTRUEmeans success andFALSEmeans failure。您应该检查所有函数调用的状态,看看它们是否返回任何错误。 -
我检查了 ReadFile 的函数调用,它返回 true。但是 hDisk 返回 0xffffffff,程序通过 if 条件并关闭句柄。什么被认为是 INVALID_HANDLE_VALUE? 0xffffffff 显然是无效的句柄值,如果条件匹配...
-
GetLastError() 函数返回 6,表示 INVALID_HANDLE_VALUE。有什么办法解决吗?