直接上程序:
1. Windows下的VC:
HANDLE hDevice = CreateFile("\\\\.\\I:", GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL
);
if (hDevice == INVALID_HANDLE_VALUE)
{
printf("打开磁盘错误\n");
return 0;
}
//读扇区
DWORD bytesread = 0;
unsigned char Buffer[1000] = {0};
int SectorNumber=0;
//for (int SectorNumber=0; SectorNumber<100; SectorNumber++)
{
SetFilePointer (hDevice, SectorNumber*512, 0, FILE_BEGIN);
ReadFile (hDevice, Buffer, 512, &bytesread, NULL);
getch();
}
//写操作
memset(Buffer, 0x35, 512);
SetFilePointer (hDevice, SectorNumber*512, 0, FILE_BEGIN);
WriteFile (hDevice, Buffer, 512, &bytesread, NULL);
上面的CreateFile函数的第一个参数,是C: ,D:类似的盘符
2. vxWorks读扇区:参考mkboot.c源程序得到
char lbaSectorZero[1024] = {0};
int line, j;
ATA_RAW ataRaw = {0};
ataRaw.cylinder = 0;
ataRaw.head = 0;
ataRaw.sector = 1;
ataRaw.pBuf = (char *)lbaSectorZero;
ataRaw.nSecs = 1;
ataRaw.direction = O_RDONLY;
ataRawio (0, 0, &ataRaw);
for(line=0; line<32; line++)
{
for(j=0; j<16; j++)
{
printf("%02x ", (unsigned char)lbaSectorZero[line*16+j]);
}
printf("\n");
}
ataRawio.direction为0时是读,为1时是写,其他参考 target/h/drv/hdisk/ataDrv.h的ATA_RAW定义。
3. Linux:下面的/dev/sde,是U盘插上去后显示的设备符合:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
/*
*
*/
int main(int argc, char** argv)
{
int fd=0;
int sizes = 0;
char buf[1000] = {0};
int line, j;
fd = open("/dev/sde", O_RDONLY);
if(fd !=-1)
{
ioctl(fd, BLKSSZGET, &sizes);
printf("sector size=%d\n", sizes);
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizes);
for(line=0; line<32; line++)
{
for(j=0; j<16; j++)
{
printf("%02x ", (unsigned char)buf[line*16+j]);
}
printf("\n");
}
}
return (EXIT_SUCCESS);
}