动态使用GetDriveType

时间:2014-09-14 03:56:24

标签: c++ winapi

我是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: %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");  
    }  
    system("pause");   
}

但是GetDriveType(myDrives)保持返回值1,即#34; No Root Directory"。如果我使用GetDriveType("C:\\"),它会显示正确的结果。我该如何解决这个问题?任何帮助将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:2)

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

  

lpRootPathName [in,optional]

     

驱动器的根目录。 :一种   需要尾随反斜杠。如果此参数为NULL,则为   function使用当前目录的根目录。

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

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

然后您可以按如下方式递增循环中的驱动器号:

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

答案 1 :(得分: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: %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 -type = %d\n", myDrives, GetDriveType(myDrives));
      }
      // increment counter for the next available drive.   
      myDrives[0]++;
      // shift the bitmask binary right    
      myDrivesBitMask >>= 1;
    }
    wprintf(L"\n");
  }
  system("pause");
}