vc下读写硬盘的操作

<span style="font-size:18px;color:#cc0000;"> </span><p><span style="font-size:18px;color:#cc0000;">vc下读写硬盘的操作,简单来说就是将硬盘当作是一个文件流来操作:</span></p><p><span style="font-size:18px;color:#cc0000;">下面是实现的函数:</span></p>
 
//drv 是盘符,一个字符,替换字符串“\\.\A:”中的字符A
//startSector 是开始扇区号
//sectors 扇区数量
//lpSectBuff 缓冲区
BOOL CRWSectorsDlg::ReadSectors(char drv, DWORD startSector, WORD sectors, LPBYTE lpSectBuff)
{
	char devName[] = "\\\\.\\A:";
	devName[4] =drv;
	
	//打开指定分区
	HANDLE hDev=CreateFile(devName, GENERIC_READ, FILE_SHARE_WRITE,NULL, OPEN_EXISTING, 0, NULL);
	if(hDev==INVALID_HANDLE_VALUE) 
		return 0;
		
	//将文件指针指向起始扇区
	SetFilePointer(hDev,512*startSector,0,FILE_BEGIN);
	DWORD dwCB;
	
	//读取指定数量的扇区
	BOOL bRet=ReadFile(hDev,lpSectBuff,512*sectors,&dwCB,NULL);
	CloseHandle(hDev);
	return bRet;
} 

BOOL CRWSectorsDlg::WriteSectors( char drv, DWORD startSector, WORD sectors, LPBYTE lpSectBuff )
{
	char devName[] = "\\\\.\\A:";
	devName[4] =drv;
	HANDLE hDev=CreateFile(devName, GENERIC_WRITE, FILE_SHARE_WRITE,NULL, OPEN_EXISTING, 0, NULL);
	if(hDev==INVALID_HANDLE_VALUE) 
		return 0;
	SetFilePointer(hDev,512*startSector,0,FILE_BEGIN);
	DWORD dwCB;
	BOOL bRet=WriteFile(hDev,lpSectBuff,512*sectors,&dwCB,NULL);
	CloseHandle(hDev);
	return bRet;

}


 

 

下边是用vc控制台程序实现的一个读取硬盘分区大小的简单代码(win7下好像不能读取到C盘的信息,暂时不知道为什么)

#include <stdio.h>
#include <stdlib.h>
#include <WTypes.h>



int main()
{
	LONGLONG lPartBegin, lPartEnd;
	DWORD dwOutByte;			// DeviceIoControl 读取的字节数
	DISK_GEOMETRY diskGeometry;
	DWORD dwSectorByte;
	HANDLE m_hDriver;
	//char Drive[] = "////.//PHYSICALDRIVE0";

	///// ("\\\\.\\D:")   // disk D:

	m_hDriver = CreateFile(("\\\\.\\D:"), GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL);
	if(m_hDriver == INVALID_HANDLE_VALUE)
	{
		return FALSE;
	}
	// GENERIC_READ FILE_SHARE_READ
	// GENERIC_WRITE FILE_SHARE_WRITE
//	ReadFile(m_hDriver, ...);


	// 读取每扇区字节数
	BOOL bDeviceRet = DeviceIoControl(m_hDriver, IOCTL_DISK_GET_DRIVE_GEOMETRY,
		NULL, 0, &diskGeometry, sizeof(DISK_GEOMETRY), &dwOutByte, NULL);

	// 每扇区字节数
	dwSectorByte = diskGeometry.BytesPerSector;

	// 读取分区大小和偏移量
	PARTITION_INFORMATION partInfo;
	bDeviceRet = DeviceIoControl(m_hDriver, IOCTL_DISK_GET_PARTITION_INFO,
		NULL, 0, &partInfo, sizeof(PARTITION_INFORMATION), &dwOutByte, NULL);

	LONGLONG lPartitionSize = partInfo.PartitionLength.QuadPart;		// 分区的大小
	LONGLONG lOffset = partInfo.StartingOffset.QuadPart;				// 偏移

	// StartingOffset 除以每扇区字节数就是开始扇区;
	// PartitionLength 除以每扇区字节数就是扇区总数。
	lPartBegin = lOffset / dwSectorByte;
	lPartEnd = lPartitionSize / dwSectorByte;

	// 开始扇区加上扇区总数再减去1就是结束扇区。
	lPartEnd += lPartBegin; //lOffset;
	lPartEnd -= 1;


	return 0;
}


 

 

 

 

 

你可能感兴趣的:(vc下读写硬盘的操作)