硬盘扇区读写

#include <iostream>
#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>
#include <vector>

//#include <QFileInfo>
//#include <QFile>
//#include <QDebug>
//#include <QDateTime>
//#include <QDataStream>
//#include <QTextStream>

using namespace std;

// WINDOWS 操作要求管理员权限
// WINDOWS 读写硬盘扇区  _test_disk_rw3( "\\\\.\\physicaldrive2" , 35469, 1 );
// WINDOWS 读写分区扇区  _test_disk_rw3( "\\\\.\\j:" , 35469, 1 );
// LINUX 读写硬盘扇区  _test_disk_rw3( "\\dev\\sda" , 35469, 1 );
// LINUX 读写分区扇区  _test_disk_rw3( "\\dev\\sda1" , 35469, 1 );
void  _test_disk_rw3 ( const char * path,
                       uint64_t sectorStart,
                       uint64_t sectorCount ,
                       const int sectorSize=512 )
{

    std::vector<char> tmp;
    std::fstream file;

    file.open( path, std::fstream::binary | std::fstream::in | std::fstream::out );

    if ( !file.is_open() )  // 判断文件是否正常打开
    {
        std::cout << "Can't open the " << path << std::endl;
        file.close();
        return ;
    }

    int64_t _offset;
    int64_t offset = sectorStart*sectorSize;
    uint64_t _sector_count=(sectorStart+sectorCount);
    uint64_t iw=sectorStart;
    uint64_t ir=sectorStart;

    std::vector<char> _by( sectorSize*sectorCount );
    _by.resize( sectorSize*sectorCount );

    std::vector<char> _cby;
    _cby.resize( sectorSize*sectorCount );
    int ret=0;

    // 备份测试扇区数据
    file.seekg( offset, std::fstream::beg );
    file.read( _by.data(), sectorSize*sectorCount ) ;
    file.seekg( offset, std::fstream::beg );


    // 生成测试数据
    char buffer[20];
    for ( uint64_t i=0; tmp.size()<sectorSize; i++ )
    {
        int l=::sprintf( buffer ,"%d", rand() );
        tmp.insert( tmp.begin(), buffer, buffer+l );
    }


    {
        ret=0;

        // 写数据到扇区
        file.seekp( offset, std::fstream::beg );
        for ( iw=sectorStart ; iw<_sector_count; )
        {
            _offset = file.tellp();
            file.write( tmp.data(), sectorSize );
            ret = file.tellp()-_offset;
            if(ret != sectorSize )
            {

            }
            iw++;
        }
        file.flush();


        // 读出刚才写入扇区的据数据
        file.seekg( offset, std::fstream::beg );
        for ( ir=sectorStart ; ir<_sector_count; )
        {
            _offset = file.tellg();
            file.read( _cby.data(), sectorSize );
            ir++;
        }


        // 备份数据恢复到扇区
        file.seekp( offset, std::fstream::beg );
        file.write( _by.data(), _by.size() );
        file.flush();

    }


    file.close();

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值