枚举系统所有驱动器名字,并计算各个驱动器的总大小和剩余大小
代码如下:
#include <vector>
#include <string>
#include <Windows.h>
#include <tchar.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR drives[128];//存储所以驱动器名称
wchar_t* pDrive;//驱动器指针
//取得系统的第一个逻辑驱动器
if (!GetLogicalDriveStrings(sizeof(drives), drives))
{
std::cout << "获取驱动器失败" << std::endl;
return false;
}
std::vector<std::wstring> diskName;
pDrive = drives; //指向第一个逻辑驱动器
while(*pDrive)
{
//将驱动器名称加入列表中
diskName.push_back(pDrive);
//指向下一个驱动器标识符
pDrive += wcslen(pDrive) + 1;
}
unsigned __int64 nFreeBytesAvailableToCaller;
unsigned __int64 nTotalNumberOfBytes;
unsigned __int64 nTotalNumberOfFreeBytes;
for (size_t i=0; i<diskName.size(); ++i)
{
std::wcout << diskName[i].c_str() << std::endl;
int ntype = GetDriveType(diskName[i].c_str());
if(ntype == DRIVE_FIXED)
{
std::cout << "硬盘" << std::endl;
}
else if(ntype == DRIVE_CDROM)
{
std::cout << "光驱" << std::endl;
}
else if(ntype == DRIVE_REMOVABLE)
{
std::cout << "可移动式磁盘" << std::endl;
}
else if(ntype == DRIVE_REMOTE)
{
std::cout << "网络磁盘" << std::endl;
}
else if(ntype == DRIVE_RAMDISK)
{
std::cout << "虚拟RAM磁盘" << std::endl;
}
else if (ntype == DRIVE_UNKNOWN)
{
std::cout << "未知设备" << std::endl;
}
//获取驱动器磁盘的空间状态
BOOL bResult = GetDiskFreeSpaceEx(
diskName[i].c_str(),
(PULARGE_INTEGER)&nFreeBytesAvailableToCaller,
(PULARGE_INTEGER)&nTotalNumberOfBytes,
(PULARGE_INTEGER)&nTotalNumberOfFreeBytes);
//判断驱动器是否在工作状态
if (bResult)
{
//磁盘总容量
std::cout << "磁盘总容量: " << (float)nTotalNumberOfBytes / 1024 / 1024 / 1024 << " GB" << std::endl;
//磁盘剩余空间
std::cout << "磁盘剩余空间: " << (float)nTotalNumberOfFreeBytes / 1024 / 1024 / 1024 << " GB" << std::endl;
}
else
{
std::cout << "设备未准备好" << std::endl;
}
}
system("pause");
return 0;
}