Recently, I had to deal with disks in windows. It took me a week to understand some basic concepts, record them here, and take some code in the project as an example.
First of all, this document does not use the cmd command line for the following reasons:
1. Calling System commands in C/C ++ is inconvenient, and a large amount of additional code is required to analyze the command execution results.
2. windows command line is far less powerful than linux shell.
3. efficiency.
Of course, if encoding is not taken into account, DiskPart is a safe and convenient option as only one of the system's application tools.
 
Let's first look at several major frequently used functions.
The most important API for dealing with disks in windows is DeviceIoControl. The following describes the function directly copied from MSDN. This function is really too important and powerful. We recommend that you read the description of this function first. Of course, this function will be widely used in subsequent examples of this article and can be returned at any time.
DeviceIoControl Function
Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
Bool winapi DeviceIoControl (
_ In HANDLE hDevice,
_ In DWORD dwIoControlCode,
_ In LPVOID lpInBuffer,
_ In DWORD nInBufferSize,
_ Out LPVOID lpOutBuffer,
_ In DWORD nOutBufferSize,
_ Out LPDWORD lpBytesReturned,
_ In LPOVERLAPPED lpOverlapped
);
Parameters
HDevice
A handle to the device on which the operation is to be operated med. the device is typically a volume, directory, file, or stream. to retrieve a device handle, use the CreateFile function. for more information, see Remarks.
DwIoControlCode
The control code for the operation. This value identifies the specific operation to be performed med and the type of device on which to perform it.
For a list of the control codes, see Remarks. The documentation for each control code provides usage details for the lpInBuffer, nInBufferSize, lpOutBuffer, and nOutBufferSize parameters.
LpInBuffer
A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.
NInBufferSize
The size of the input buffer, in bytes.
LpOutBuffer
A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.
NOutBufferSize
The size of the output buffer, in bytes.
LpBytesReturned
A pointer to a variable that sums es the size of the data stored in the output buffer, in bytes.
If the output buffer is too small to receive any data, the call fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and lpBytesReturned is zero.
If the output buffer is too small to hold all of the data but can hold some entries, some drivers will return as much data as fits. in this case, the call fails, GetLastError returns ERROR_MORE_DATA, and lpBytesReturned indicates the amount of data already ed. your application shocould call DeviceIoControl again with the same operation, specifying a new starting point.
If lpOverlapped is NULL, lpBytesReturned cannot be NULL. even when an operation returns no output data and lpOutBuffer is NULL, DeviceIoControl makes use of lpBytesReturned. after such an operation, the value of lpBytesReturned is meaningless.
If lpOverlapped is not NULL, lpBytesReturned can be NULL. if this parameter is not NULL and the operation returns data, lpBytesReturned is meaningless until the overlapped operation has completed. to retrieve the number of bytes returned, call GetOverlappedResult. if hDevice is associated with an I/O completion port, you can retrieve the number of bytes returned by calling GetQueuedCompletionStatus.
LpOverlapped
A pointer to an OVERLAPPED structure.
If hDevice was opened without specifying FILE_FLAG_OVERLAPPED, lpOverlapped is ignored.
If hDevice was opened with the FILE_FLAG_OVERLAPPED flag, the operation is performed med as an overlapped (asynchronous) operation. in this case, lpOverlapped must point to a valid OVERLAPPED structure that contains a handle to an event object. otherwise, the function fails in unpredictable ways.
For overlapped operations, DeviceIoControl returns immediately, and the event object is signaled when the operation has been completed. Otherwise, the function does not return until the operation has been completed or an error occurs.
Return Value
If the operation completes successfully, the return value is nonzero.
If the operation fails or is pending, the return value is zero. To get extended error information, call GetLastError.
Remarks
To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the driver associated with a device. to specify a device name, use the following format:
\. \ DeviceName
DeviceIoControl can accept a handle to a specific device. for example, to open a handle to the logical drive A: with CreateFile, specify \\. \ :. alternatively, you can use the names \\. \ PhysicalDrive0 ,\\. \ PhysicalDrive1, and so on, to open handles to the physical drives on a system.
You shoshould specify the file_cmd_read and file_cmd_write access flags when calling CreateFile to open a handle to a device driver. however, when you open a communications resource, such as a serial port, you must specify exclusive access. use the other CreateFile parameters as follows when opening a device handle:
· The fdwCreate parameter must specify OPEN_EXISTING.
· The hTemplateFile parameter must be NULL.
· The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped (asynchronous) I/O operations.
Requirements
Client
Requires Windows Vista, Windows XP, Windows 2000 Professional, or Windows NT Workstation.
Server
Requires Windows Server 2008, Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header
Declared in Winbase. h; include Windows. h.
Library
Use Kernel32.lib.
DLL
Requires Kernel32.dll.
 
This function allows you to access devices, including obtaining information, sending commands, and exchanging data. You can use this interface function to send the correct control code and data to the specified device driver, analyze its response, and execute the functions that the program designer wants. Disk operations are only a small part of its powerful functions.
The two most important parameters of this function are hDevice and dwIoControlCode.
 
The control code dwIoControlCode determines the operation type. The disk-related control codes include
IOCTL_DISK_CREATE_DISK uses the information in the CREATE_DISK structure to initialize the specified disk and disk partition.
IOCTL_DISK_DELETE_DRIVE_LAYOUT deletes the boot information from the Master Boot Record, so the disk will be formatted from start to end. Partition information in sector 0 no longer exists.
IOCTL_DISK_FORMAT_TRACKS format the specified, continuous floppy disk track. If you need more functions, use IOCTL_DISK_FORMAT_TRACKS_EX.
IOCTL_DISK_FORMAT_TRACKS_EX format the specified, continuous floppy disk track.
IOCTL_DISK_GET_CACHE_INFORMATION returns the disk's high-speed cache configuration data
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX returns the extended information of the physical disk. Including: type, number of cylinders, number of tracks per cylinder, number of sectors per track, and number of bytes per sector.
IOCTL_DISK_GET_DRIVE_LAYOUT_EX returns the extended information of each partition and its features. For more information, see the DRIVE_LAYOUT_INFORMATION_EX structure.
IOCTL_DISK_GET_LENGTH_INFO returns the size of the specified Disk/volume/partition.
IOCTL_DISK_GET_PARTITION_INFO_EX returns the extended information of the specified partition. Including partition type, size, and type. For more information, see the PARTITION_INFORMATION_EX structure.
IOCTL_DISK_GROW_PARTITION expands the specified partition.
IOCTL_DISK_IS_WRITABLE: determines whether the specified disk is writable.
Enable IOCTL_DISK_PERFORMANCE and obtain disk Performance Statistics
Ioctl_disk_cece_off disable disk Performance Statistics
IOCTL_DISK_REASSIGN_BLOCKS uses a disk device as its backup storage block public pool (spare block pool ).
IOCTL_DISK_SET_CACHE_INFORMATION
IOCTL_DISK_SET_DRIVE_LAYOUT_EX partitions the disk based on the given disk information.
IOCTL_DISK_SET_PARTITION_INFO_EX sets the partition information of the specified partition. Including the layout information of AT and EFI (Extensible Firmware Interface) partitions.
IOCTL_DISK_UPDATE_PROPERTIES invalidates the buffered Partition Table and obtains a new copy.
IOCTL_DISK_VERIFY
 
 
Another hDevice parameter points to the device handle to be operated and is obtained by calling the CreateFile function. The CreateFile function is prototype
Handle winapi CreateFile (
_ In LPCTSTR lpFileName,
_ In DWORD dwDesiredAccess,
_ In DWORD dw1_mode,
_ In LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_ In DWORD dwCreationDisposition,
_ In DWORD dwFlagsAndAttributes,
_ In HANDLE hTemplateFile
);
LpFileName is the name of the device to be opened. For disks, it may take the following forms:
For physical drive x, the format is \. \ PhysicalDriveX. The number starts from 0, for example
 
 
 
 
 
 
  
   
   | Name | Description | 
 
   
   | \. \ PhysicalDrive0 | Open the first physical drive | 
 
   
   | \\. \ PhysicalDrive2 | Open the third physical drive | 
 
  
 
For logical partitions (volumes), the format is \. \ X:, for example
 
 
 
 
  
   
   | Name | Description | 
 
   
   | \. \: | Open drive) | 
 
   
   | \. \ C: | Open disk C (logical partition of disk) | 
 
  
 
Finally, copy the sample code on MSDN to end this section. This example obtains the disk details (including the cylindrical, track, sector, and other statistical information) and prints it out.
 
/* The code of interest is in the subroutine GetDriveGeometry.
Code in main shows how to interpret the results of the call .*/
 
# Include <windows. h>
# Include <winioctl. h>
# Include <stdio. h>
 
BOOL GetDriveGeometry (DISK_GEOMETRY * pdg)
{
HANDLE hDevice; // handle to the drive to be examined
BOOL bResult; // results flag
DWORD junk; // discard results
 
HDevice = CreateFile (TEXT ("\\\\. \ PhysicalDrive0"), // drive
0, // no access to the drive
File_cmd_read | // share mode
File_pai_write,
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL); // do not copy file attributes
 
If (hDevice = INVALID_HANDLE_VALUE) // cannot open the drive
{
Return (FALSE );
}
 
BResult = DeviceIoControl (hDevice, // device to be queried
IOCTL_DISK_GET_DRIVE_GEOMETRY, // operation to perform
NULL, 0, // no input buffer
Pdg, sizeof (* pdg), // output buffer
& Junk, // # bytes returned
(LPOVERLAPPED) NULL); // synchronous I/O
 
CloseHandle (hDevice );
 
Return (bResult );
}
 
Int main (int argc, char * argv [])
{
DISK_GEOMETRY pdg; // disk drive geometry structure
BOOL bResult; // generic results flag
ULONGLONG DiskSize; // size of the drive, in bytes
 
BResult = GetDriveGeometry (& pdg );
 
If (bResult)
{
Printf ("Cylinders = % I64d \ n", pdg. Cylinders );
Printf ("Tracks/cylinder = % ld \ n", (ULONG) pdg. TracksPerCylinder );
Printf ("Sectors/track = % ld \ n", (ULONG) pdg. SectorsPerTrack );
Printf ("Bytes/sector = % ld \ n", (ULONG) pdg. BytesPerSector );
 
DiskSize = pdg. Cylinders. QuadPart * (ULONG) pdg. TracksPerCylinder *
(ULONG) pdg. SectorsPerTrack * (ULONG) pdg. BytesPerSector;
Printf ("Disk size = % I64d (Bytes) = % I64d (Gb) \ n", DiskSize,
DiskSize/(1024*1024*1024 ));
}
Else
{
Printf ("GetDriveGeometry failed. Error % ld. \ n", GetLastError ());
}
 
Return (int) bResult );
}
 
 
This article is from the "bunny's technology Journey" blog