动态使用GetDriveType

Dynamically using GetDriveType

本文关键字:GetDriveType 动态      更新时间:2023-10-16

我是WIN32 C++的新手。我想做的是使用GetDriveType函数动态定义每个驱动器的类型。

这是我的代码

#include Windows.h 
#include stdio.h 
#include iostream 
using namespace std; 
int main()
{
    // Initial Dummy drive
    WCHAR myDrives[] = L" A";  
    // Get the logical drive bitmask (1st drive at bit position 0, 2nd drive at bit position 1... so on)  
    DWORD myDrivesBitMask = GetLogicalDrives();  
    // Verifying the returned drive mask  
    if(myDrivesBitMask == 0)   
        wprintf(L"GetLogicalDrives() failed with error code: %dn", 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 %sn", myDrives);    
            }    
            // increment counter for the next available drive.   
            myDrives[1]++;    
            // shift the bitmask binary right    
            myDrivesBitMask >>= 1;   
        }   
        wprintf(L"n");  
    }  
    system("pause");   
}

GetDriveType(myDrives)一直返回值1,即"无根目录"。如果我像GetDriveType("C:\")一样使用,它会显示正确的结果。我该如何解决这个问题?如有任何帮助,我们将不胜感激。

感谢

您的myDrive[]初始化数据有两个问题。它在驱动器号之前有一个额外的空间,并且没有在驱动器号之后指定冒号反斜杠。GetDriveType()的文档中明确提到:

lpRootPathName[in,可选]

驱动器的根目录A尾部反斜杠是必需的如果此参数为NULL,则函数使用当前目录的根目录。

您应该修改myDrives的声明如下:

// Initial Dummy drive
    WCHAR myDrives[] = L"A:\";  

然后你可以在循环中增加驱动器号,如下所示:

// increment counter for the next available drive.   
    myDrives[0]++; 

您在myDrives中有一个前导空格。GetDriveType()不忽略前导空格。删除它,您的代码就会工作。参见以下工作示例:

#include <Windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
  // Initial Dummy drive
  WCHAR myDrives[] = L"A:\";
  // Get the logical drive bitmask (1st drive at bit position 0, 2nd drive at bit position 1... so on)  
  DWORD myDrivesBitMask = GetLogicalDrives();
  // Verifying the returned drive mask  
  if (myDrivesBitMask == 0)
    wprintf(L"GetLogicalDrives() failed with error code: %dn", 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 -type = %dn", myDrives, GetDriveType(myDrives));
      }
      // increment counter for the next available drive.   
      myDrives[0]++;
      // shift the bitmask binary right    
      myDrivesBitMask >>= 1;
    }
    wprintf(L"n");
  }
  system("pause");
}