Archive

Posts Tagged ‘GetLogicalDriveStrings’

CD ROM present in CD Drive?

Good question! The easiest and working method is to call GetVolumeInformation on a CD-Drive, this function call will fail if no valid volume information is available for a drive this means CD-ROM drive should be valid one too!

So our next job is to find out whether we have a CD-Drive in our machine, for this purpose we iterate through all available drives and use GetDriveType( lpctszDrive ) == DRIVE_CDROM.

As always with me here is a function for this purpose…

bool Is_CD_ROM_Present()
{
   // Drive buffer
   TCHAR szLogicalDrives[MAX_PATH] = { 0 };

   // Get all drives in our computer, each drive is separated by NULL char
   GetLogicalDriveStrings( MAX_PATH, szLogicalDrives );

   // Value to return, provided to handle multiple CD-ROM drives,
   // if any of them contains a CD-ROM then we return true
   bool RetVal = false;

   // Temp var which helps us in looping through the drive buffer, sicne each drive is
   // NULL separated.
   LPTSTR lptszDrive = szLogicalDrives;
   while( *lptszDrive )
   {
      // Check whether it's a CD-ROM
      if( GetDriveType( lptszDrive ) == DRIVE_CDROM )
      {
         // We don't want a message box to pop up requesting us to insert a CD-ROM,
         // so set error mode accordingly
         const UINT PrevErrMode = SetErrorMode( SEM_FAILCRITICALERRORS );
         const bool RetValTemp = ( GetVolumeInformation( lptszDrive, 0, 0, 0, 0, 0, 0, 0 ) != 0 );

         // To handle multiple CD-ROM drives
         RetVal = RetVal || RetValTemp;

         // Restore error mode
         SetErrorMode( PrevErrMode );
      }// fi

      // Get next drive by moving one char ahead of "NULL" separator between drives
      lptszDrive += _tcslen( lptszDrive ) + 1;
   }// wend

   return RetVal;
}// End Is_CD_ROM_Present
Advertisements

Using GetLogicalDriveStrings!

I’ve seen people getting stuck with this API mainly because each drive given in the output buffer from this API is NULL terminated and the last entry is double NULL terminated.

So how to extract drives from this API’s output buffer. Here is the code snippet that does this…

TCHAR szDrives[MAX_PATH] = { 0 };
if( GetLogicalDriveStrings( MAX_PATH, szDrives ))
{
   LPTSTR lptszOneDrive = szDrives;
   while( *lptszOneDrive )
   {
      // Do something with one drive
      MessageBox( 0, lptszOneDrive, _T( "Drives" ), MB_OK );

      // Get next drive
      const int nOffset = _tcslen( lptszOneDrive ) + 1;
      lptszOneDrive += nOffset;
   }// End while
}// End if
%d bloggers like this: