Windows下获取磁盘信息

发布于 2020-12-01  132 次阅读


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#include <iostream>
using namespace std;

#include <Windows.h>

void putDrivesType(const TCHAR* lpRootPathName)
{
	UINT uDriverType = GetDriveType(lpRootPathName);

	switch (uDriverType)
	{
		case DRIVE_UNKNOWN:puts("未知的磁盘类型"); break;
		case DRIVE_NO_ROOT_DIR: puts("路径无效"); break;
		case DRIVE_REMOVABLE: puts("可移动磁盘"); break;
		case DRIVE_FIXED: puts("固定磁盘"); break;
		case DRIVE_REMOTE: puts("网络磁盘"); break;
		case DRIVE_CDROM: puts("光驱"); break;
		case DRIVE_RAMDISK: puts("内存映射盘"); break;
		default: break;
	}

}

void putDrivesFreeSpace(const TCHAR* lpRootPathName)
{
	unsigned long long available, total, free;
	if (GetDiskFreeSpaceEx(lpRootPathName, (ULARGE_INTEGER*)&available, (ULARGE_INTEGER*)&total, (ULARGE_INTEGER*)&free))
	{
		printf("Drives %s | total = %lld MB,available = %lld MB,free = %lld MB\n",
			lpRootPathName, total >> 20, available >> 20, free >> 20);
	}
	else
	{
		puts("获取容量信息失败");
	}
}

int main(int argc, const char *argv[])
{
	DWORD dwSize = MAX_PATH;
	TCHAR szLogicalDrives[MAX_PATH] = { 0 };
	//获取逻辑驱动器号字符串
	DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives);
	//处理获取到的结果
	if (dwResult > 0 && dwResult <= MAX_PATH) {
		TCHAR* szSingleDrive = szLogicalDrives;  //从缓冲区起始地址开始
		while(*szSingleDrive) {
			printf("Drive: %s; ", szSingleDrive);   //输出单个驱动器的驱动器号
			putDrivesType(szSingleDrive);           //输出逻辑驱动器类型
			putDrivesFreeSpace(szSingleDrive);

			// 获取下一个驱动器号起始地址
			szSingleDrive += lstrlen(szSingleDrive) + 1;
		}
	}

	system("pause");
	return EXIT_SUCCESS;
}