Created
November 18, 2017 04:57
-
-
Save igaozp/eadf29426f69cabf11c96fb9467eaa99 to your computer and use it in GitHub Desktop.
读取磁盘信息
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <windows.h> | |
| #include <iostream.h> | |
| #include <winioctl.h> | |
| #include <string.h> | |
| //关于Disk结构的定义 | |
| struct Disk | |
| { | |
| HANDLE handle; | |
| DISK_GEOMETRY disk_info; | |
| }; | |
| static Disk physicDisk(char driverLetter); | |
| int main(int argc, char* argv[]) | |
| { | |
| Disk disk; | |
| char DriverLetter; | |
| cout << "请输入磁盘号:c/d/e/f" << endl; | |
| cin >> DriverLetter; // 选择要查看的磁盘 | |
| disk = physicDisk(DriverLetter); | |
| return 0; | |
| } | |
| static Disk physicDisk(char driverLetter) | |
| { | |
| Disk disk; | |
| _int64 sector; | |
| bool flag; | |
| HANDLE Floppy; | |
| flag = true; | |
| DISK_GEOMETRY* temp = new DISK_GEOMETRY; | |
| char device[9] = "\\\\.\\c:"; | |
| device[4] = driverLetter; | |
| Floppy = CreateFile(device, | |
| GENERIC_READ | GENERIC_WRITE, | |
| FILE_SHARE_READ | FILE_SHARE_WRITE, | |
| NULL, | |
| OPEN_EXISTING, | |
| FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_NO_BUFFERING, | |
| NULL); | |
| if (GetLastError() == ERROR_ALREADY_EXISTS) // 如打开失败,返回错误代码 | |
| { | |
| cout << "不能打开磁盘" << endl; | |
| cout << GetLastError() << endl; | |
| flag = false; | |
| return disk; | |
| } | |
| DWORD bytereturned; | |
| BOOL Result; | |
| disk.handle = Floppy; | |
| Result = DeviceIoControl(Floppy, | |
| IOCTL_DISK_GET_DRIVE_GEOMETRY, | |
| NULL, | |
| 0, | |
| temp, | |
| sizeof(*temp), | |
| &bytereturned, | |
| (LPOVERLAPPED)NULL); | |
| if (!Result) // 如果失败,返回错误代码 | |
| { | |
| cout << "打开失败" << endl; | |
| cout << "错误代码为:" << GetLastError() << endl; | |
| flag = false; | |
| return disk; | |
| } | |
| disk.disk_info = *temp; // 输出整个物理磁盘的信息 | |
| cout << driverLetter << "盘有: " << endl; | |
| cout << "柱面数为:" << (unsigned long)disk.disk_info.Cylinders.QuadPart << endl; | |
| cout << "每柱面的磁道数为:" << disk.disk_info.TracksPerCylinder << endl; | |
| cout << "每磁道的扇区数为:" << disk.disk_info.SectorsPerTrack << endl; | |
| cout << "每扇区的字节数为:" << disk.disk_info.BytesPerSector << endl; | |
| // 计算总扇区数 | |
| sector = disk.disk_info.Cylinders.QuadPart* (disk.disk_info.TracksPerCylinder)* (disk.disk_info.SectorsPerTrack); | |
| // 计算总字节数 | |
| double DiskSize = (double)sector * | |
| (disk.disk_info.BytesPerSector) / | |
| (1024 * 1024 * 1024); | |
| cout << driverLetter << "盘所在磁盘总共有" << (long)sector << "个扇区" << endl; | |
| cout << "磁盘大小为:" << DiskSize << "GB " << endl; | |
| delete temp; | |
| return disk; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment