751k8 发表于 2012-4-10 17:09:22

vc++直接读写物理扇区源码,xp下编译通过!

#include <stdio.h>
#include <string.h>
#include <iostream.h>
#include <windows.h>

BOOL ReadPhysicalSector(unsigned long SectorStart, unsigned long SectorCount, unsigned char *p)
{
        unsigned long BytesPerSector = 512;
    unsigned long nBytes;
    char Drive[] = "\\\\.\\PhysicalDrive0";//注意物理磁盘的大小写,这样才是正确的
    BOOL result = FALSE;
    HANDLE hDeviceHandle = CreateFile(Drive,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,0);
    if(hDeviceHandle)
    {
      long pointer;
      long phigh;
      pointer = SectorStart;
      pointer = pointer*BytesPerSector;
      phigh = pointer>>32;
      SetFilePointer(hDeviceHandle,(unsigned long)pointer,&phigh,FILE_BEGIN);
      if(ReadFile(hDeviceHandle,p,SectorCount*BytesPerSector,&nBytes,NULL))
            result = TRUE;
      CloseHandle(hDeviceHandle);
    }
    return result;
}
BOOL WritePhysicalSector(unsigned long SectorStart, unsigned long SectorCount, unsigned char *p)
{
        unsigned long BytesPerSector = 512;
    unsigned long nBytes;
    char Drive[] = "\\\\.\\PhysicalDrive0";//注意物理磁盘的大小写,这样才是正确的
    BOOL result = FALSE;
    HANDLE hDeviceHandle = CreateFile(Drive,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,0);
    if(hDeviceHandle)
    {
      long pointer;
      long phigh;
      pointer = SectorStart;
      pointer = pointer*BytesPerSector;
      phigh = pointer>>32;
      SetFilePointer(hDeviceHandle,(unsigned long)pointer,&phigh,FILE_BEGIN);
      if(WriteFile(hDeviceHandle,p,SectorCount*BytesPerSector,&nBytes,NULL))
            result = TRUE;
      CloseHandle(hDeviceHandle);
    }
    return result;
}

//调用就这样
int main(int argc, char* argv[])
{
    unsigned long SectorStart = 0;//比如我要读的是编号为的那个扇区开始的数据,这里写
                                  //如果读的是从第扇区开始后的数据这里就写
    unsigned long SectorCount = 1;//读多少个扇区,这里是个
    unsigned char p;//一个扇区数据量是字节呀
    ReadPhysicalSector(SectorStart, SectorCount, p);读第0扇区
    WritePhysicalSector(5,1,p);写到第5扇区
}

xiongdeyuan 发表于 2012-4-10 20:50:46

好的.支持下

a501237260 发表于 2012-5-31 21:17:50

不错。。。。。。。。。

丁刚 发表于 2012-6-5 16:19:05

我真的想学习一下

fidonet 发表于 2012-6-5 18:32:57

好贴,绝对要支持下!!~~

ikkyphoenix 发表于 2013-7-9 17:44:44

好帖,必须顶起!

onflypuma 发表于 2013-11-27 18:08:12

谢谢分享!

程同太 发表于 2014-1-2 21:09:26

好东西!值得收藏

the263 发表于 2015-6-15 15:17:08

毫不犹豫的收藏了。
页: [1]
查看完整版本: vc++直接读写物理扇区源码,xp下编译通过!