Get partitions of a hard disk drive

Share your advanced PureBasic knowledge/code with the community.
hoangdiemtinh
User
User
Posts: 29
Joined: Wed Nov 16, 2022 1:51 pm

Re: Get partitions of a hard disk drive

Post by hoangdiemtinh »

@doctorized

I tested on Windows 10 x64 (PB 6 x64), run it as admin.
Result: DeviceIoControl return 0 for GPT Disks, so I can not get disk information
Please review and fix.

Code: Select all

Structure PARTITION_INFORMATION
  StartingOffset.q
  PartitionLength.q
  HiddenSectors.l
  PartitionNumber.l
  PartitionType.b
  BootIndicator.b
  RecognizedPartition.b
  RewritePartition.b
  dummy.l
EndStructure

Structure DRIVE_LAYOUT_INFORMATION 
  PartitionCount.l
  Signature.l
  PartitionEntry.PARTITION_INFORMATION[50]
EndStructure

Procedure.s GetPartitionType(type.b)
  Select type
    Case 0
      ProcedureReturn "Unused"
    Case 1
      ProcedureReturn "12-bit FAT"
    Case 2, 3
      ProcedureReturn "Xenix"
    Case 4
      ProcedureReturn "16-bit FAT"
    Case 5
      ProcedureReturn "Extended"
    Case 6
      ProcedureReturn "Huge partition MS-DOS V4"
    Case 7
      ProcedureReturn "Installable File System (NTFS/HPFS/FAT64)"
    Case 8
      ProcedureReturn "OS/2 (v1.0-1.3 only)/AIX boot partition/Commodore DOS/SplitDrive/DELL partition spanning multiple drives/QNX 1.x and 2.x (qny)"
    Case 9
      ProcedureReturn "AIX data partition/Coherent filesystem/QNX 1.x and 2.x (qnz)"
    Case $A
      ProcedureReturn "OS/2 Boot Manager/OPUS/Coherent swap"
    Case $B
      ProcedureReturn "FAT32"
    Case $C
      ProcedureReturn "FAT32 using extended int13 services"
    Case $E
      ProcedureReturn "Win95 partition using extended int13 services"
    Case $F
      ProcedureReturn "Extended using extended int13 services"
    Case $41
      ProcedureReturn "PowerPC Reference Platform (PReP) Boot Partition"
    Case $42
      ProcedureReturn "Logical Disk Manager partition"
    Case $63
      ProcedureReturn "Unix"
    Case $C0
      ProcedureReturn "NTFT uses high order bits"
    Case $80
      ProcedureReturn "NTFT"
  EndSelect
EndProcedure

IOCTL_DISK_GET_DRIVE_LAYOUT.l = 475148
aa.DRIVE_LAYOUT_INFORMATION
BytesRet.l:tmp.l
For ii=0 To 49
  BytesRet = 0: tmp = 0
  hdh.l = CreateFile_("\\.\PhysicalDrive" + Str(ii),#GENERIC_READ | #GENERIC_WRITE, #FILE_SHARE_READ | #FILE_SHARE_WRITE,0, #OPEN_EXISTING, 0, 0)
  DeviceIoControl_(hdh,IOCTL_DISK_GET_DRIVE_LAYOUT, #Null,0,@aa, SizeOf(DRIVE_LAYOUT_INFORMATION), @BytesRet,0)
  
  If BytesRet > 0
    Debug "disk #" + Str(ii)
    Debug "==============="
    For i=0 To aa\PartitionCount-1
      If aa\PartitionEntry[i]\RecognizedPartition = 1
        tmp + 1
        Debug "Partition #" + Str(tmp) + "  :  " + GetPartitionType(aa\PartitionEntry[i]\PartitionType) + "  , length  =  " + Str(aa\PartitionEntry[i]\PartitionLength) + " bytes"
      EndIf
    Next
    Debug ""
  EndIf
Next
Post Reply