-2

I have code to get the drive letter. This code in my system is good, but it isn't working in virtual machine(VMWare) :

std::vector<TCHAR*> DrivesName = { _T("A:\\"), _T("B:\\"), _T("C:\\"), _T("D:\\"), _T("E:\\"),
    _T("F:\\"), _T("G:\\"), _T("H:\\"), _T("I:\\"), _T("J:\\"),
    _T("K:\\"), _T("L:\\"), _T("M:\\"), _T("N:\\"), _T("O:\\"),
    _T("P:\\"), _T("Q:\\"), _T("R:\\"), _T("S:\\"), _T("T:\\"),
    _T("U:\\"), _T("V:\\"), _T("W:\\"), _T("X:\\"), _T("Y:\\"), _T("Z:\\") };

DWORD drivesBitmask = GetLogicalDrives();
if (drivesBitmask == 0)
{
    std::cout << "ERROR";
}

for (int i = 0; i < 26; i++)
{
    if ((drivesBitmask & 1) == 0)
    {
        if (typeDriver != DRIVE_NO_ROOT_DIR) 
        {
            std::cout << "Drive: " << DrivesName[i] << std::endl;
        }
    }
}

I changed (drivesBitmask & 1) == 0 condition to (drivesBitmask & 2) == 0 it work, but i don't understand....

what is different?

  • 1
    Your check `if ((drivesBitmask & 1) == 0)` doesn't depend from `i` (besides not making any sense at all) ... How can it be correct? – Matteo Italia Dec 30 '17 at 12:10
  • 3
    Read your code and think about it. The expression in your if statement has the same value for each iteration of the for loop. That expression tests whether or not your machine has an A drive. You need to test `(1 << i) & drivesBitmask`. And the driver name vector is rather pointless. You can use `L'A' + i`. Don't use TCHAR, use wchar_t. You. Don't need to cater for Windows 98. – David Heffernan Dec 30 '17 at 12:10
  • 4
    (incidentally, that `DrivesName` vector makes kittens cry) – Matteo Italia Dec 30 '17 at 12:12
  • Besides, those `DriveNames` are neither drive names nor volume names. Those are directory names. – IInspectable Dec 30 '17 at 18:12
  • 1
    You can get rid of `DrivesName` and just use `... << 'A' + i << ":\\" << ...` instead. Or use `GetLogicalDriveStrings()` instead and forget all this bit twiddling – Remy Lebeau Dec 30 '17 at 20:51

1 Answers1

4

You're not testing correctly, so you end up printing all drives as existing based on whether or not the A drive exists (and the test is reversed, so it prints only if A does not exist; I'm guessing that's the difference between your systems).

To fix, change the test to use i to test each bit sequentially, not the same bit over and over, and avoid inverting the test (caused by comparing to 0 instead of checking for non-zero value), changing:

if ((drivesBitmask & 1) == 0)

to:

if (drivesBitmask & (1 << i))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271