windows的磁盤操作之二——初始化磁盤

上一節中我們介紹了一些基本概念和主要的API,本節開始我們將列舉並分析一些實例。本文中的所有代碼我都在vs2008下測試過,讀者只需要替換少量的宏定義即可編譯執行。

 
面對一塊新的磁盤,我們首先要做的就是對其初始化。在系統中通過windows的磁盤管理完成這一點非常容易,但在程序中實現略微複雜。本節的示例代碼對一塊新硬盤初始化,並在上面創建分區。
代碼如下:
 
/******************************************************************************
* Function: initialize the disk and create partitions
* input: disk, disk name
*        parNum, partition number
* output: N/A
* return: Succeed, 0
*         Fail, -1
******************************************************************************/
DWORD CreateDisk(DWORD disk, WORD partNum)
{
    HANDLE hDevice;               // handle to the drive to be examined
    BOOL result;                  // results flag
    DWORD readed;                 // discard results
    DWORD ret;
    WORD i;
    CHAR diskPath[DISK_PATH_LEN];
    DISK_GEOMETRY pdg;
    DWORD sectorSize;
    DWORD signature;
    LARGE_INTEGER diskSize;
    LARGE_INTEGER partSize;
    BYTE actualPartNum;
   
    DWORD layoutStructSize;
    DRIVE_LAYOUT_INFORMATION_EX *dl;
    CREATE_DISK newDisk;
 
    sprintf(diskPath, "\\\\.\\PhysicalDrive%d", disk);
 
    actualPartNum = 4;
    if (partNum > actualPartNum)
    {
        return (WORD)-1;
    }
   
    hDevice = CreateFile(
                diskPath,
                GENERIC_READ|GENERIC_WRITE,
                FILE_SHARE_READ|FILE_SHARE_WRITE,
                NULL,           //default security attributes  
                OPEN_EXISTING, // disposition  
                0,              // file attributes  
                NULL
                );
    if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
    {
        fprintf(stderr, "CreateFile() Error: %ld\n", GetLastError());
        return DWORD(-1);
    }
   
    // Create primary partition MBR
    newDisk.PartitionStyle = PARTITION_STYLE_MBR;
    signature = (DWORD)time(NULL);     //get signature from current time
    newDisk.Mbr.Signature = signature;
   
    result = DeviceIoControl(
                hDevice,
                IOCTL_DISK_CREATE_DISK,
                &newDisk,
                sizeof(CREATE_DISK),
                NULL,
                0,
                &readed,
                NULL
                );
    if (!result)
    {
        fprintf(stderr, "IOCTL_DISK_CREATE_DISK Error: %ld\n", GetLastError());
        (void)CloseHandle(hDevice);
        return DWORD(-1);
    }
 
    //fresh the partition table
    result = DeviceIoControl(
                hDevice,
                IOCTL_DISK_UPDATE_PROPERTIES,
                NULL,
                0,
                NULL,
                0,
                &readed,
                NULL
                );
    if (!result)
    {
        fprintf(stderr, "IOCTL_DISK_UPDATE_PROPERTIES Error: %ld\n", GetLastError());
        (void)CloseHandle(hDevice);
        return DWORD(-1);
    }
 
    //Now create the partitions
    ret = GetDriveGeometry(diskPath, &pdg);
    if ((DWORD)-1 == ret)
    {
        return ret;
    }
    sectorSize = pdg.BytesPerSector;
    diskSize.QuadPart = pdg.Cylinders.QuadPart * pdg.TracksPerCylinder *
                        pdg.SectorsPerTrack * pdg.BytesPerSector;       //calculate the disk size;
    partSize.QuadPart = diskSize.QuadPart / partNum;
 
    layoutStructSize = sizeof(DRIVE_LAYOUT_INFORMATION_EX) + (actualPartNum - 1) * sizeof(PARTITION_INFORMATION_EX);
    dl = (DRIVE_LAYOUT_INFORMATION_EX*)malloc(layoutStructSize);
    if (NULL == dl)
    {
        (void)CloseHandle(hDevice);
        return (WORD)-1;
    }
 
    dl->PartitionStyle = (DWORD)PARTITION_STYLE_MBR;
    dl->PartitionCount = actualPartNum;
    dl->Mbr.Signature = signature;
 
    //clear the unused partitions
    for (i = 0; i < actualPartNum; i++){
        dl->PartitionEntry[i].RewritePartition = 1;
        dl->PartitionEntry[i].Mbr.PartitionType = PARTITION_ENTRY_UNUSED;
    }
    //set the profile of the partitions
    for (i = 0; i < partNum; i++){
        dl->PartitionEntry[i].PartitionStyle = PARTITION_STYLE_MBR;
        dl->PartitionEntry[i].StartingOffset.QuadPart =
            (partSize.QuadPart * i) + ((LONGLONG)(pdg.SectorsPerTrack) * (LONGLONG)(pdg.BytesPerSector));   //32256
        dl->PartitionEntry[i].PartitionLength.QuadPart = partSize.QuadPart;
        dl->PartitionEntry[i].PartitionNumber = i + 1;
        dl->PartitionEntry[i].RewritePartition = TRUE;
        dl->PartitionEntry[i].Mbr.PartitionType = PARTITION_IFS;
        dl->PartitionEntry[i].Mbr.BootIndicator = FALSE;
        dl->PartitionEntry[i].Mbr.RecognizedPartition = TRUE;
        dl->PartitionEntry[i].Mbr.HiddenSectors =
            pdg.SectorsPerTrack + (DWORD)((partSize.QuadPart / sectorSize) * i);
    }
    //execute the layout  
    result = DeviceIoControl(
                hDevice,
                IOCTL_DISK_SET_DRIVE_LAYOUT_EX,
                dl,
                layoutStructSize,
                NULL,
                0,
                &readed,
                NULL
                );
    if (!result)
    {
        fprintf(stderr, "IOCTL_DISK_SET_DRIVE_LAYOUT_EX Error: %ld\n", GetLastError());
        free(dl);
        (void)CloseHandle(hDevice);
        return DWORD(-1);
    }
 
    //fresh the partition table
    result = DeviceIoControl(
                hDevice,
                IOCTL_DISK_UPDATE_PROPERTIES,
                NULL,
                0,
                NULL,
                0,
                &readed,
                NULL
                );
    if (!result)
    {
        fprintf(stderr, "IOCTL_DISK_UPDATE_PROPERTIES Error: %ld\n", GetLastError());
        free(dl);
        (void)CloseHandle(hDevice);
        return DWORD(-1);
    }
 
    free(dl);
    (void)CloseHandle(hDevice);
    Sleep(3000);            //wait the operations take effect
    return 0;
}
 
函數CreateDisk包含兩個參數,
DWORD disk 填入物理驅動器號,參見第一節。
WORD partNum 表示需要創建的分區數,partNum <= 4
 
函數的執行流程解釋如下:
/***************初始化磁盤*****************/
1. 根據disk創建設備名稱,\\\\.\\PhysicalDriveX,這裏由於要轉義,所以”\”都寫爲”\\”
2. 調用CreateFile打開設備文件,並獲得句柄。
3. 用操作碼IOCTL_DISK_CREATE_DISK調用DeviceIoControl函數,初始化磁盤並創建分區表。
使用IOCTL_DISK_CREATE_DISK操作碼時,lpInBuffer要填入一個CREATE_DISK結構參數,其中包括分區表類型和磁盤簽名等參數,詳見MSDN。本例中創建MBR分區表,簽名由當前時間產生。
4. 刷新分區表。注意,程序中任何時候對磁盤的分區信息進行了修改都需要調用操作碼爲IOCTL_DISK_UPDATE_PROPERTIESDeviceIoControl函數來刷新分區表,是操作切實生效。
/****************創建分區*******************/
5. 調用GetDriveGeometry獲取磁盤信息(GetDriveGeometry參見上一節http://cutebunny.blog.51cto.com/301216/624027)。由於創建分區時要填入分區大小信息,我們此處先計算磁盤總大小,然後除以partNum將字節數平均分配到各個分區。
6. 分配DRIVE_LAYOUT_INFORMATION_EX結構體空間。我們通過在這個結構體中填入數據來指定如何對硬盤進行分區。結構體定義如下
typedef struct _DRIVE_LAYOUT_INFORMATION_EX {
DWORD PartitionStyle;
DWORD PartitionCount;
union {
    DRIVE_LAYOUT_INFORMATION_MBR Mbr;
    DRIVE_LAYOUT_INFORMATION_GPT Gpt;
};
PARTITION_INFORMATION_EX PartitionEntry[1];
} DRIVE_LAYOUT_INFORMATION_EX,
 *PDRIVE_LAYOUT_INFORMATION_EX;
       其中PartitionCount4的倍數,爲簡化處理,我們這裏定死爲4
       另外還要注意PARTITION_INFORMATION_EX型的數組PartitionEntry[1]。雖然結構體中只定義了一個元素,但事實上必須在其後補足PartitionCount – 1個元素。所以代碼中爲DRIVE_LAYOUT_INFORMATION_EX *dl分配空間的時候加上了(actualPartNum - 1) * sizeof(PARTITION_INFORMATION_EX)
7. DRIVE_LAYOUT_INFORMATION_EX結構體空間dl中填入數據。
先將所有分區都設爲PARTITION_ENTRY_UNUSED,後面具體分配多少個分區再設置回來。
然後再循環體內對每個分區的PartitionEntry賦值,其中
StartingOffset除了跳過前面的分區已佔據的空間外,還要加上63個扇區空間(32256字節)。
PartitionNumber1開始。
Mbr.PartitionType = PARTITION_IFS表示NTFS格式。
Mbr.HiddenSectors MSDN上說The number of hidden sectors to be allocated when the partition table is created. 我理解得不是很深刻,歡迎補充。
8. 調用操作碼爲IOCTL_DISK_SET_DRIVE_LAYOUT_EXDeviceIoControl函數執行分區,參數需要填入剛纔準備好的DRIVE_LAYOUT_INFORMATION_EX結構體和大小。
9. 刷新分區表,原理同4
另外,我在函數末尾加上了Sleep(3000)。這是因爲我發現創建分區操作需要一定的執行時間,如果後續緊跟着其它相關操作(例如格式化該分區)可能會產生分區不存在的錯誤,所以此處等待3秒確保其執行完畢。
本節涉及的類型較多,但各類型具有很強的關聯性,讀者可隨時查閱MSDN獲得更詳細的說明。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章