我对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,即“无根目录”。如果我像GetDriveType("C:\\")这样使用,它会显示正确的结果。我该如何解决这个问题?任何帮助,将不胜感激。

谢谢

最佳答案

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");
}

关于c++ - 动态使用GetDriveType,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25829931/

10-11 01:32