I'm trying to initialize a disk, partition and format it in NTFS or FAT32 format, but I encountered some problems. The code can initialize a disk and partition it, but after code execution the disk start sector data was wrong. Here is the code.
int InitDisk(void)
{
BOOL bResult = FALSE; CAutoFile hDevice; DWORD junk = 0;
hDevice = CreateFile(TEXT("\\\\.\\PhysicalDrive0"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) {
return GetLastError();
}
CREATE_DISK dsk;
dsk.PartitionStyle = PARTITION_STYLE_MBR;
dsk.Mbr.Signature = 9999;
bResult = DeviceIoControl(hDevice, IOCTL_DISK_CREATE_DISK, &dsk, sizeof(dsk), NULL, 0, &junk, NULL);
if (!bResult)
{
return GetLastError();
}
bResult = DeviceIoControl(hDevice,
IOCTL_DISK_UPDATE_PROPERTIES,
NULL, 0, NULL, 0, &junk, NULL);
if (! bResult)
{
return GetLastError();
}
LARGE_INTEGER lgPartitionSize;
lgPartitionSize.QuadPart = (1024 * 1024 * 1024);
DWORD dwDriverLayoutInfoExLen = sizeof (DRIVE_LAYOUT_INFORMATION_EX) + 3 * sizeof(PARTITION_INFORMATION_EX);
DRIVE_LAYOUT_INFORMATION_EX *pdg = (DRIVE_LAYOUT_INFORMATION_EX *)new BYTE[dwDriverLayoutInfoExLen];
if (pdg == NULL)
{
return -1;
}
SecureZeroMemory(pdg, dwDriverLayoutInfoExLen);
pdg->PartitionStyle = PARTITION_STYLE_MBR;
pdg->PartitionCount = 1;
pdg->Mbr.Signature = 99999;
pdg->PartitionEntry[0].PartitionStyle = PARTITION_STYLE_MBR;
pdg->PartitionEntry[0].StartingOffset.QuadPart = 32256; pdg->PartitionEntry[0].PartitionLength.QuadPart = lgPartitionSize.QuadPart * 36;
pdg->PartitionEntry[0].PartitionNumber = 1;
pdg->PartitionEntry[0].RewritePartition = TRUE;
pdg->PartitionEntry[0].Mbr.PartitionType = PARTITION_NTFT; pdg->PartitionEntry[0].Mbr.BootIndicator = TRUE;
pdg->PartitionEntry[0].Mbr.RecognizedPartition = 1;
pdg->PartitionEntry[0].Mbr.HiddenSectors = 32256 / 512;
bResult = DeviceIoControl(hDevice, IOCTL_DISK_SET_DRIVE_LAYOUT_EX, pdg, sizeof DRIVE_LAYOUT_INFORMATION_EX, NULL, 0, &junk, NULL);
if (!bResult)
{
return GetLastError();
}
bResult = DeviceIoControl(hDevice,
IOCTL_DISK_UPDATE_PROPERTIES,
NULL, 0, NULL, 0, &junk, NULL);
if (!bResult)
{
return GetLastError();
}
PARTITION_INFORMATION_EX dskinfo;
PARTITION_INFORMATION_MBR mbrinfo;
mbrinfo.PartitionType = PARTITION_NTFT;
mbrinfo.HiddenSectors = (32256 / 512);
mbrinfo.BootIndicator = 1;
mbrinfo.RecognizedPartition = 1;
dskinfo.PartitionStyle = PARTITION_STYLE_MBR;
dskinfo.StartingOffset.QuadPart = 32256;
dskinfo.PartitionLength.QuadPart = lgPartitionSize.QuadPart * 36;
dskinfo.PartitionNumber = 1;
dskinfo.RewritePartition = TRUE;
dskinfo.Mbr = mbrinfo;
bResult = DeviceIoControl(hDevice, IOCTL_DISK_SET_PARTITION_INFO_EX, &dskinfo, sizeof(dskinfo), NULL, 0, &junk, NULL);
if (!bResult)
{
return GetLastError();
}
return 0;
}
Hope that friends who have some experience can guide me!
Format the partition function does not call SHFormatDrive Shell API!