2017-02-19 2 views
0

Helo,с ++ окна передать результат от GetLogicalDrives к GetVolumeInformation

Im используя GetLogicalDrives, чтобы получить все диски, и я хочу использовать это в дальнейшем для определения типа привода, а затем проверить состояние конкретного диска, используя GetVolumeInformation , Тем не менее, я не могу использовать результат GetLogicalDrives (DWORD) в GetVolumeInformation и GetDriveTypes, поскольку они рассматривают LPCWSTR. Как я могу преобразовать результат из GetLogicalDrives и передать его GetVolumeInformation и GetDriveTypes?

 TCHAR myDrives[] = L" A"; 
     DWORD myDrivesBitMask = GetLogicalDrives(); 
     WCHAR szTest[10]; 



     if (myDrivesBitMask == 0) 
wprintf(L"GetLogicalDrives() failed with error code: %d\n", GetLastError()); 
     else { 
      wprintf(L"This machine has the following logical drives:\n"); 
      while (myDrivesBitMask) { 
       // Use the bitwise AND with 1 to identify 
       // whether there is a drive present or not. 
       if (myDrivesBitMask & 1) { 
        // Printing out the available drives     
        wprintf(L"drive %s\n", myDrives); 
       } 
       // increment counter for the next available drive. 
       myDrives[1]++; 
       // shift the bitmask binary right  
       myDrivesBitMask >>= 1; 
      } 
      wprintf(L"\n"); 
     } 
UINT test; 
for (i = 0; i<12; i++) 
    { 
     test = GetDriveType(myDrives[i]); 
     switch (test) 
     { 
     case 0: printf("Drive %S is type %d - Cannot be determined.\n", myDrives[i], test); 
      break; 
     case 1: printf("Drive %S is type %d - Invalid root path/Not available.\n", myDrives[i], test); 
      break; 
     case 2: printf("Drive %S is type %d - Removable.\n", myDrives[i], test); 
      break; 
     case 3: printf("Drive %S is type %d - Fixed.\n", myDrives[i], test); 
      break; 
     case 4: printf("Drive %S is type %d - Network.\n", myDrives[i], test); 
      break; 
     case 5: printf("Drive %S is type %d - CD-ROM.\n", myDrives[i], test); 

      break; 
     case 6: printf("Drive %S is type %d - RAMDISK.\n", myDrives[i], test); 
      break; 
     default: "Unknown value!\n"; 
     } 
    } 



    (GetVolumeInformation(myDrives, volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponentLen, &fileSystemFlags, fileSystemName, ARRAYSIZE(fileSystemName))) 
      { 
       _tprintf(_T("There is a CD/DVD in the CD/DVD rom")); 
       _tprintf(_T("Volume Name: %s\n"), volumeName); 
       _tprintf(_T("Serial Number: %lu\n"), serialNumber); 
       _tprintf(_T("File System Name: %s\n"), fileSystemName); 
       _tprintf(_T("Max Component Length: %lu\n"), maxComponentLen); 

      } 
      else 
       _tprintf(_T("There is NO CD/DVD in the CD/DVD rom")); 
+1

С помощью [ 'GetLogicalDriveStrings'] (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364975 (v = vs.85) .aspx) вместо' GetLogicalDrives'. –

+3

Или просто скопируйте номер диска '0' в' A: \ 'и так далее (в алфавитном порядке). –

+1

Для современных Windows вещи можно значительно упростить, просто используя Unicode (тип 'wchar_t'), вместо макросов совместимости с Windows 9x, таких как' TCHAR'. В конце концов, ваша toolchain, вероятно, даже не может создать исполняемый файл Windows 9x. Так что все это не имеет ничего общего, кроме усложнения вещей. –

ответ

2

С вам потребуются буквы дисков, чтобы позвонить GetDriveType() и GetVolumeInformation(), было бы проще использовать GetLogicalDriveStrings() вместо GetLogicalDrives(), например:

WCHAR myDrives[105]; 
WCHAR volumeName[MAX_PATH]; 
WCHAR fileSystemName[MAX_PATH]; 
DWORD serialNumber, maxComponentLen, fileSystemFlags; 
UINT driveType; 

if (!GetLogicalDriveStringsW(ARRAYSIZE(myDrives)-1, myDrives)) 
{ 
    wprintf(L"GetLogicalDrives() failed with error code: %lu\n", GetLastError()); 
} 
else 
{ 
    wprintf(L"This machine has the following logical drives:\n"); 

    for (LPWSTR drive = myDrives; *drive != 0; drive += 4) 
    { 
     driveType = GetDriveTypeW(drive); 
     wprintf(L"Drive %s is type %d - ", drive, driveType); 

     switch (driveType) 
     { 
      case DRIVE_UNKNOWN: 
       wprintf(L"Cannot be determined!"); 
       break; 
      case DRIVE_NO_ROOT_DIR: 
       wprintf(L"Invalid root path/Not available."); 
       break; 
      case DRIVE_REMOVABLE: 
       wprintf(L"Removable."); 
       break; 
      case DRIVE_FIXED: 
       wprintf(L"Fixed."); 
       break; 
      case DRIVE_REMOTE: 
       wprintf(L"Network."); 
       break; 
      case DRIVE_CDROM: 
       wprintf(L"CD-ROM."); 
       break; 
      case DRIVE_RAMDISK: 
       wprintf(L"RAMDISK."); 
       break; 
      default: 
       wprintf(L"Unknown value!"); 
     } 
     wprintf(L"\n"); 

     if (driveType == DRIVE_CDROM) 
     { 
      if (GetVolumeInformationW(drive, volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponentLen, &fileSystemFlags, fileSystemName, ARRAYSIZE(fileSystemName))) 
      { 
       wprintf(L" There is a CD/DVD in the drive:\n"); 
       wprintf(L" Volume Name: %s\n", volumeName); 
       wprintf(L" Serial Number: %08X\n", serialNumber); 
       wprintf(L" File System Name: %s\n", fileSystemName); 
       wprintf(L" Max Component Length: %lu\n", maxComponentLen); 
      } 
      else 
      { 
       wprintf(L" There is NO CD/DVD in the drive"); 
      } 
     } 
    } 
} 
+0

Спасибо. Я очень ценю, что вы нашли время, чтобы сделать этот пример. Это упрощает код. – user1754598

1

Я хотел бы создать функцию-оболочку для GetLogicalDrives(), чтобы получить более простой в обращении вектор привода трактов:

std::vector<std::wstring> GetLogicalDrivePathes() 
{ 
    std::vector<std::wstring> result; 

    DWORD mask = GetLogicalDrives(); 
    for(wchar_t drive = 'A'; drive <= 'Z'; ++drive) 
    { 
     if(mask & 1) 
     { 
      std::wstring rootPath; 
      rootPath += drive; 
      rootPath += L":\\"; 
      result.push_back(rootPath); 
     } 
     mask >>= 1; 
    } 

    return result; 
} 

Он может быть использован, как это:

for(auto& path : GetLogicalDrivePathes()) 
{ 
    test = GetDriveType(path.data()); 

} 
+2

'GetLogicalDriveStrings()' значительно упростит 'GetLogicalDrivePathes()'. –

+1

Я ненавижу строки с двойным нулевым завершением, и я хотел придерживаться функции, используемой OP, чтобы показать, как ее можно заставить работать. Если вам нравится, вы можете опубликовать ответ, показывающий, как использовать GetLogicalDriveStrings() в качестве альтернативы. – zett42

+0

Спасибо, этот пример действительно помог. – user1754598

Смежные вопросы