原創作品,允許轉載,轉載時請務必以超連結形式標明文章
原始出處 、作者資訊和本聲明。否則將追究法律責任。http://cutebunny.blog.51cto.com/301216/624027
最近項目中需要在windows系統下與磁碟打交道,用了一個禮拜時間,弄懂了一些基本的概念,記錄於此,並以項目中的部分代碼作為範例。
首先說明一點,本文中使用的不是cmd命令列,基於以下幾點原因:1.在C/C++中調用系統命令會存在處理的種種不方便,需要大量額外的代碼去分析命令執行結果。2.windows命令列遠不如linux的shell來的強大。3.效率。當然,如果不考慮編碼,僅作為系統下一種應用工具的話,DiskPart是既安全又便利的選擇。 我們先來看幾個主要的使用頻繁的函數。在windows下與磁碟打交道最主要的API就是DeviceIoControl了,以下是從MSDN中直接拷貝出來的對該函數的說明。此函數確實太重要也太強大了,建議大家耐著性子先將它的說明看完,當然,本文後續例子中會大量用到此函數,可隨時返回此節參閱。
DeviceIoControl FunctionSends 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 performed. 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 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.
lpBytesReturnedA pointer to a variable that receives 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 received. Your application should 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 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 ValueIf 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.
RemarksTo 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:\\.\
DeviceNameDeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to open
handles to the physical drives on a system.You should specify the FILE_SHARE_READ and FILE_SHARE_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. |
該函數實現對裝置的訪問,包括擷取資訊,發送命令,交換資料等。可以利用該介面函數向指定的裝置驅動發送正確的控制碼及資料,分析它的響應,執行程式設計人員想要的功能。磁碟操作只是它強大功能中的一小部分。該函數最重要的兩個參數是hDevice和dwIoControlCode. 控制碼dwIoControlCode決定了操作類型,與磁碟相關的控制碼有IOCTL_DISK_CREATE_DISK 利用CREATE_DISK結構中的資訊對指定磁碟和磁碟分割進行初始化。IOCTL_DISK_DELETE_DRIVE_LAYOUT 從主引導記錄中刪除引導資訊,所以磁碟將會被從頭到尾的格式化。扇區0中的分區資訊也就不複存在了。IOCTL_DISK_FORMAT_TRACKS 格式化指定的、連續的磁碟片磁軌。如果需要更多的功能請使用IOCTL_DISK_FORMAT_TRACKS_EX。IOCTL_DISK_FORMAT_TRACKS_EX 格式化指定的、連續的磁碟片磁軌。IOCTL_DISK_GET_CACHE_INFORMATION 返回磁碟的快取配置資料IOCTL_DISK_GET_DRIVE_GEOMETRY_EX 返回物理磁碟的擴充資訊。包括:類型、柱面數量、每柱面磁軌數、每磁軌扇區數和每扇區位元組數等。IOCTL_DISK_GET_DRIVE_LAYOUT_EX 返回各分區的擴充資訊以及這些分區的特性。更多資訊請參照DRIVE_LAYOUT_INFORMATION_EX結構。IOCTL_DISK_GET_LENGTH_INFO 返回指定磁碟/卷/分區的大小資訊IOCTL_DISK_GET_PARTITION_INFO_EX 返回指定分區的擴充資訊。包括:分區類型、大小和種類。更多資訊請參照PARTITION_INFORMATION_EX結構。IOCTL_DISK_GROW_PARTITION 擴大指定分區。IOCTL_DISK_IS_WRITABLE 確定指定磁碟是否可寫。IOCTL_DISK_PERFORMANCE 啟用並擷取磁碟效能統計IOCTL_DISK_PERFORMANCE_OFF 關閉磁碟效能統計IOCTL_DISK_REASSIGN_BLOCKS 使磁碟裝置影射一塊地區做為它的備用儲存塊公用池(spare block pool)。IOCTL_DISK_SET_CACHE_INFORMATION 設定磁碟的配置資訊IOCTL_DISK_SET_DRIVE_LAYOUT_EX 根據給定的磁碟資訊對磁碟進行分區。IOCTL_DISK_SET_PARTITION_INFO_EX 設定指定分區的分區資訊。包括AT和EFI (Extensible Firmware Interface)分區的布局資訊。IOCTL_DISK_UPDATE_PROPERTIES 使緩衝的分區表無效並重新擷取一份。IOCTL_DISK_VERIFY 對指定磁碟進行邏輯格式化
另一個參數hDevice指向要操作的裝置控制代碼,調用函數CreateFile獲得。CreateFile函數原型為HANDLE WINAPI CreateFile( __in LPCTSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in HANDLE hTemplateFile);lpFileName為需要開啟裝置的名稱,對於磁碟來說,可能為以下幾種形式:對於物理磁碟機x,形式為 \\.\PhysicalDriveX ,編號從0開始,例如
名稱 |
含義 |
\\.\PhysicalDrive0 |
開啟第一個物理磁碟機 |
\\.\PhysicalDrive2 |
開啟第三個物理磁碟機 |
對於邏輯分區(卷),形式為 \\.\X: ,例如
名稱 |
含義 |
\\.\A: |
開啟A盤(軟碟機) |
\\.\C: |
開啟C盤(磁碟邏輯分區) |
最後複製一段MSDN上的範例程式碼作為本節的結束,該樣本擷取磁碟的詳細資料(包括柱面、磁軌、扇區等統計資訊)並列印出來。 /* The code of interest is in the subroutine GetDriveGeometry. The 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_SHARE_READ | // share mode FILE_SHARE_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);}
本文出自 “bunny技術坊” 部落格,請務必保留此出處http://cutebunny.blog.51cto.com/301216/624027