VC下獲取各個驅動器路徑,分類及其獲取其信息的資料整理 1.獲取所有的驅動器 利用函數 GetLogicalDriveStrings
size_t szAllDriveStrings = GetLogicalDriveStrings(0,NULL);
//返回字符串的長度
The GetLogicalDriveStrings function fills a buffer with strings that specify valid drives in the system.
DWORD GetLogicalDriveStrings( DWORD nBufferLength, // size of buffer LPTSTR lpBuffer // drive strings buffer );
很簡單的一個函數,msdn有詳細的說明 需要注意的一點是
lpBuffer中最後獲得的數據是這樣c:/<null>d:/<null><null>,每兩個路徑之間都間隔一個 null-terminated, 所以,如果你直接cout<<lpBuffer 的話,那麼得到的是C:/,很是令人鬱悶,於是要想辦法把這些路徑一個一個取得
所以,有了如下代碼 TCHAR szBuf[100]; memset(szBuf,0,100); DWORD len = GetLogicalDriveStrings(sizeof(szBuf)/sizeof(TCHAR),szBuf);
for (TCHAR* s = szBuf; *s; s += _tcslen(s)+1) { LPCTSTR sDrivePath = s;
cout<<sDrivePath }
那麼這個sDrivePath 就是一個一個的類似於C:/,D:/那樣的字符竄
2.獲取驅動器類型 現在獲得了驅動器的路徑了,如C:/,D:/ 那麼如何區分他們呢, 有這個函數
GetDriveType The GetDriveType function determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.
UINT GetDriveType( LPCTSTR lpRootPathName // root directory );
UINT uDriveType = GetDriveType(sDrivePath); 調用以後,這個函數的返回值有
Value Meaning DRIVE_UNKNOWN The drive type cannot be determined. DRIVE_NO_ROOT_DIR The root path is invalid. For example, no volume is mounted at the path. DRIVE_REMOVABLE The disk can be removed from the drive. DRIVE_FIXED The disk cannot be removed from the drive. DRIVE_REMOTE The drive is a remote (network) drive. DRIVE_CDROM The drive is a CD-ROM drive. DRIVE_RAMDISK The drive is a RAM disk.
但是,靠這個函數,很多東西,都是區分不了了,比如軟驅,和插入的U盤,都是DRIVE_REMOVABLE ,而硬盤和插入的移動硬盤,都是DRIVE_FIXED 靠:(
我們一個一個來試試吧
3.獲取光驅 先捏軟柿子:)
UINT uDriveType = GetDriveType(sDrivePath);
if (uDriveType == DRIVE_CDROM) { 這個就是咯 }
要注意的是,雖然寫的是DRIVE_CDROM 但是dvd 光驅也能獲得(這不廢話嗎),另外,虛擬光驅也能獲得,比如俺機器上安裝了Alcohol 120%,設置的虛擬光驅也獲得了
4.區分軟驅和U盤
先把代碼貼出來吧 #define MEDIA_INFO_SIZE sizeof(GET_MEDIA_TYPES)+15*sizeof(DEVICE_MEDIA_INFO)
BOOL GetDriveGeometry(const TCHAR * filename, DISK_GEOMETRY * pdg) { HANDLE hDevice; // 設備句柄 BOOL bResult; // DeviceIoControl的返回結果 GET_MEDIA_TYPES *pmt; // 內部用的輸出緩衝區 DWORD dwOutBytes; // 輸出數據長度
// 打開設備 hDevice = ::CreateFile(filename, // 文件名 GENERIC_READ, // 軟驅需要讀盤 FILE_SHARE_READ | FILE_SHARE_WRITE, // 共享方式 NULL, // 默認的安全描述符 OPEN_EXISTING, // 創建方式 0, // 不需設置文件屬性 NULL); // 不需參照模板文件
if (hDevice == INVALID_HANDLE_VALUE)
|