One of Windows disk operations-Basic Concepts

Source: Internet
Author: User
Original Works are allowed to be reprinted. During reprinting, please mark the article in hyperlink form
Original source, author information, and this statement. Otherwise, legal liability will be held. Http://cutebunny.blog.51cto.com/301216/624027

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 requires a large amount of additional code 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 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 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
Lpinbuffer, Ninbuffersize, Lpoutbuffer, And NoutbuffersizeParameters. 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
DwiocontrolcodeParameter. This parameter can be null if DwiocontrolcodeSpecifies 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
DwiocontrolcodeParameter. This parameter can be null if DwiocontrolcodeSpecifies an operation that does not return data. Noutbuffersize
The size of the output buffer, in bytes. LpbytesreturnedA 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
LpbytesreturnedIs 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
LpbytesreturnedIndicates the amount of data stored ed. Your application shocould call deviceiocontrol again with the same operation, specifying a new starting point. If LpoverlappedIs null, LpbytesreturnedCannot be null. Even when an operation returns no output data and
LpoutbufferIs null, deviceiocontrol makes use Lpbytesreturned. After such an operation, the value
LpbytesreturnedIs meaningless. If LpoverlappedIs not null, LpbytesreturnedCan be null. If this parameter is not null and the operation returns data,
LpbytesreturnedIs meaningless until the overlapped operation has completed. to retrieve the number of bytes returned, call getoverlappedresult. If
HdeviceIs 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 HdeviceWas opened without specifying file_flag_overlapped,
LpoverlappedIs ignored. If HdeviceWas opened with the file_flag_overlapped flag, the operation is performed med as an overlapped (asynchronous) operation. In this case,
LpoverlappedMust 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 \\. \ :. 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: · FdwcreateParameter must specify open_existing. · HtemplatefileParameter must be null. · FdwattrsandflagsParameter 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 code ioctl_disk_create_disk initializes the specified disk and disk partition using the information in the create_disk structure. 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 information 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. Ioctl_disk_performance enable and obtain disk Performance Statistics ioctl_disk_performance_off disable disk Performance Statistics ioctl_disk_reassign_blocks enable the disk device to picture an area as its backup storage block public pool (spare block pool ). Ioctl_disk_set_cache_information sets the disk configuration information ioctl_disk_set_drive_layout_ex to partition 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 dwcreation, _ in DWORD dwflagsandattributes, _ in handle htemplatefile); lpfilename indicates the name of the device to be opened. For disks, it may take the following forms: for physical drive X, the format is \\. \ physicaldrivex, number starting 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. 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_0000_read | // share mode file_0000_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 Technology Workshop" blog, please be sure to keep this source http://cutebunny.blog.51cto.com/301216/624027

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.