本版
查看: 5061|回复: 3

简单MBR读取库的实现

[复制链接]

[Lv.7]特大萝卜

楼主(1#)
发表于 2016-7-31 22:27:19 | 只看该作者 |只看大图 |倒序浏览 |阅读模式
本帖最后由 20011010wo 于 2016-7-31 23:01 编辑

  1. <div class="blockcode"><blockquote>#define WIN32_LEAN_AND_MEAN

    #include <windows.h>
    #include <io.h>
    #include <sys\stat.h>
    #include <sys\types.h>
    #include <share.h>
    #include <fcntl.h>
    #include <cstdlib>

    #include <string>
    struct MBRPartitionTable
    {
    unsigned char bootsign;
    unsigned char start_chsaddress[3];
    unsigned char type;
    unsigned char end_chsaddress[3];
    unsigned char used_sectorsnum[4];
    unsigned char total_sectorsnum[4];
    };
    struct MBR
    {
    unsigned char bootstrapcode[446];
    MBRPartitionTable a;
    MBRPartitionTable b;
    MBRPartitionTable c;
    MBRPartitionTable d;
    unsigned char endsign[2];
    };
    // 物理驱动器对象
    class PhysicalDrive
    {
    public:
    PhysicalDrive(void) : drive(L"\\\\.\\PhysicalDrive"), drive_index(0){} //构造函数
    std::wstring GetDriveName(void) //获取存储设备名称
    {
    wchar_t drive_index_buffer[8];
    _itow_s(drive_index, drive_index_buffer, 8, 10); //int 转 wcahr_t
    return drive + drive_index_buffer;
    }
    private:
    std::wstring drive; //存储设备部分名称
    int drive_index; //存储设备号
    };

    class Libmbr {
    public:
    Libmbr(void) = delete; //不允许合成构造函数
    Libmbr(PhysicalDrive); //构造函数
    bool ReadMBR(); //读MBR函数
    bool WriteMBR(); //写MBR函数
    MBR code = {0}; //将要写入的数据
    private:
    bool ReadWriteMBR(bool); //内部实现函数
    PhysicalDrive m_drive; //存储设备对象
    int iFileHandler; //文件句柄
    };

  1. #include "libmbr.h"



    inline Libmbr::Libmbr(PhysicalDrive drive) :m_drive(drive) {} //构造函数

    inline bool Libmbr::ReadMBR()
    {
    return ReadWriteMBR(true);
    }

    inline bool Libmbr::WriteMBR()
    {
    return ReadWriteMBR(false);
    }


    bool Libmbr::ReadWriteMBR(bool isRead)
    {
    //打开设备
    if (_wsopen_s(&iFileHandler, m_drive.GetDriveName().c_str(), _O_BINARY | _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE))
    return false;
    //判断是否至EOF
    if (_eof(iFileHandler))
    return false;
    //移动至起始点
    if (_lseek(iFileHandler, 0, SEEK_SET) == -1)
    return false;
    //读写属性
    if (isRead)
    {
    if (_read(iFileHandler, &code, 512) == -1) //读512个字
    return false;
    }
    else
    {
    if (_write(iFileHandler, &code, 512) == -1) //写512个字
    return false;
    }
    //刷新设备缓冲
    if (_commit(iFileHandler) == -1)
    return false;
    //关闭句柄
    if (_close(iFileHandler) == -1)
    return false;
    return true;
    }


回复

支持 | 反对  0 支持 / 0 反对 评分 举报

[Lv.7]特大萝卜

沙发(2#)
 楼主| 发表于 2016-7-31 22:32:35 | 只看该作者
补充:还有数据结构还没加入

[Lv.7]特大萝卜

板凳(3#)
 楼主| 发表于 2016-7-31 23:02:10 | 只看该作者
加入了

Super Moderator

地板(4#)
发表于 2016-7-31 23:12:54 | 只看该作者
赞~

联系我们(Contact)|手机版|萝卜头IT论坛 ( 苏ICP备15050961号-1 )

GMT+8, 2026-10-19 03:19 , Processed in 0.07 second(s), 20 queries , Gzip On.

快速回复 返回顶部 返回列表