• <ul id="mayc0"></ul>
    <ul id="mayc0"><center id="mayc0"></center></ul>
    <strike id="mayc0"><input id="mayc0"></input></strike>
    <ul id="mayc0"></ul>
  • 始創于2000年 股票代碼:831685
    咨詢熱線:0371-60135900 注冊有禮 登錄
    • 掛牌上市企業
    • 60秒人工響應
    • 99.99%連通率
    • 7*24h人工
    • 故障100倍補償
    您的位置: 網站首頁 > 幫助中心>文章內容

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

    發布時間:  2012/9/11 19:39:50

      上一節中我們介紹了一些基本概念和主要的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 ", 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 ", 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 ", 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 ", 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 ", 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_PROPERTIES的DeviceIoControl函數來刷新分區表,是操作切實生效。
      /****************創建分區*******************/
      5. 調用GetDriveGeometry獲取磁盤信息(GetDriveGeometry參見上一節)。由于創建分區時要填入分區大小信息,我們此處先計算磁盤總大小,然后除以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;
      其中PartitionCount為4的倍數,為簡化處理,我們這里定死為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字節)。
      PartitionNumber從1開始。
      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_EX的DeviceIoControl函數執行分區,參數需要填入剛才準備好的DRIVE_LAYOUT_INFORMATION_EX結構體和大小。
      9. 刷新分區表,原理同4。
      另外,我在函數末尾加上了Sleep(3000)。這是因為我發現創建分區操作需要一定的執行時間,如果后續緊跟著其它相關操作(例如格式化該分區)可能會產生分區不存在的錯誤,所以此處等待3秒確保其執行完畢。

    億恩科技地址(ADD):鄭州市黃河路129號天一大廈608室 郵編(ZIP):450008 傳真(FAX):0371-60123888
       聯系:億恩小凡
       QQ:89317007
       電話:0371-63322206


    本文出自:億恩科技【www.vbseamall.com】

    服務器租用/服務器托管中國五強!虛擬主機域名注冊頂級提供商!15年品質保障!--億恩科技[ENKJ.COM]

  • 您可能在找
  • 億恩北京公司:
  • 經營性ICP/ISP證:京B2-20150015
  • 億恩鄭州公司:
  • 經營性ICP/ISP/IDC證:豫B1.B2-20060070
  • 億恩南昌公司:
  • 經營性ICP/ISP證:贛B2-20080012
  • 服務器/云主機 24小時售后服務電話:0371-60135900
  • 虛擬主機/智能建站 24小時售后服務電話:0371-60135900
  • 專注服務器托管17年
    掃掃關注-微信公眾號
    0371-60135900
    Copyright© 1999-2019 ENKJ All Rights Reserved 億恩科技 版權所有  地址:鄭州市高新區翠竹街1號總部企業基地億恩大廈  法律顧問:河南亞太人律師事務所郝建鋒、杜慧月律師   京公網安備41019702002023號
      0
     
     
     
     

    0371-60135900
    7*24小時客服服務熱線