#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();
}
硬盘扇区读写
于 2024-07-23 21:33:32 首次发布