Windows平台下使用C++检测硬盘分区是否属于SSD硬盘的方法

#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <string>
#include <cassert>

typedef std::basic_string<TCHAR> StringT;

bool IsDriveSSD(const StringT& driveName)
{
    assert(driveName.size()>=2);

    HANDLE hDevice = CreateFile((_T("\\\\.\\") + driveName.substr(0, 2)).c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

    if (hDevice == INVALID_HANDLE_VALUE)
    {
        return false;
    }

    STORAGE_PROPERTY_QUERY query{};
    query.PropertyId = StorageDeviceSeekPenaltyProperty;
    query.QueryType = PropertyStandardQuery;
    DWORD count;
    DEVICE_SEEK_PENALTY_DESCRIPTOR result{};
    if (DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
        &query, sizeof(query), &result, sizeof(result), &count, nullptr))
    {
        CloseHandle(hDevice);
        return !result.IncursSeekPenalty;
    }

    CloseHandle(hDevice);

    return false;
}

int main()
{
    DWORD len = GetLogicalDriveStrings(0, NULL);
    if (len == 0)
    {
        return 0;
    }

    TCHAR* buffer = new TCHAR[len];
    
    GetLogicalDriveStrings(len, buffer);

    for (TCHAR* drive = buffer; *drive; drive += _tcslen(drive) + 1)
    {
        // ULARGE_INTEGER freeBytesAvailable;
        // ULARGE_INTEGER totalNumberOfBytes;
        // ULARGE_INTEGER totalNumberOfFreeBytes;

        // if (GetDiskFreeSpaceEx(drive, &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
        {
        #if UNICODE
        #define  _tcout std::wcout
        #else
        #define  _tcout std::cout
        #endif

            _tcout << drive << _T("  ") << (IsDriveSSD(drive)?_T("True") : _T("False")) << std::endl;
        }
    }

    delete[] buffer;

    return 0;
}

 

输出:

C:\  True
D:\  False
E:\  False
F:\  False
G:\  True
H:\  True
I:\  True

 

posted @ 2024-05-30 11:36  bodong  阅读(175)  评论(0编辑  收藏  举报