Using _getdrives() function

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Listing the logical drives on local machine

To show: Using _getdrives()

 

 

// Listing the available drive using _getdrives()

#include <windows.h>

#include <direct.h>

#include <stdio.h>

#include <tchar.h>

 

// Buffer, be careful with terminated NULL. Must match with ++mydrives[1], that is a space

// Example if no space: "A:"--> ++mydrives[0];

char mydrives[] = " A: ";

// Or char mydrives[] = {" A: "};

// Or TCHAR mydrives[] = " A: ";

 

int main(void)

{

// Get the drives bit masks...1 is available, 0 is not available

// A = least significant bit...

ULONG DriveMask = _getdrives();

// Check, if something wrong

if(DriveMask == 0)

printf("_getdrives() failed with failure code: %d\n", GetLastError());

else

{

printf("This machine has the following logical drives:\n");

while (DriveMask)

{ // List all the drives...

if(DriveMask & 1)

printf("%s", mydrives);

// Go to the next drive strings with one space

++mydrives[1];

// Shift the bit masks binary to the right and repeat

DriveMask >>= 1;

}

printf("\n");

}

return 0;

}

 

 

Output example:

 

 

This machine has the following logical drives:

A: C: E: F: G: J: K:

Press any key to continue . . .

 

 

Note: A: is floppy, J: is USB's thumb drive and K: is CDRW

 

 

C and C++ Programming Resources | C & C++ Code Example Index