Helper classes for Logic Drive and Volume enumeration in Win32

Logical Drive Enumeration

//
// Enumerates Logical Drives on the Host Computer
//
class CLogicalDrives
{
  DWORD m_dwDrives;
  DWORD m_dwDriveIndex;
public:
  inline CLogicalDrives()
  {
    m_dwDriveIndex = 0;
    m_dwDrives  = GetLogicalDrives();
  }
  inline int GetFirstLogicalDrive()
  {
    m_dwDriveIndex = 0;
    m_dwDrives  = GetLogicalDrives();
    while(m_dwDrives)
    {
      if(m_dwDrives & 1)
        return m_dwDriveIndex;
      m_dwDriveIndex++;
      m_dwDrives >>= 1;
    }
    return -1;
  }

  inline int GetNextLogicalDrive()
  {
    do
    {
      m_dwDriveIndex++;
      m_dwDrives >>= 1;
      if(m_dwDrives & 1)
        return m_dwDriveIndex;
    }while(m_dwDrives);

    return -1;
  }
  inline CString GetFirstLogicalDriveString()
  {		
    int nDriveIndex = GetFirstLogicalDrive();
    if(nDriveIndex >= 0)
      return TCHAR(_T('A') + nDriveIndex) + CString(_T(":\\"));
    return _T("");
  }
  inline CString GetNextLogicalDriveString()
  {
    int nDriveIndex = GetNextLogicalDrive();
    if(nDriveIndex >= 0)
      return TCHAR(_T('A') + nDriveIndex) + CString(_T(":\\"));
    return _T("");
  }
};

Volume Enumeration

//
// Enumerates Volumes of the Host Computer
//
class CVolumeEnumerator
{
  enum {	BUFSIZE	= 1024,	ERRBUFSIZE = 1024 };

  HANDLE	m_hFindVolume;
  TCHAR	m_szVolumeName[BUFSIZE];
  TCHAR	m_szErrMsg[ERRBUFSIZE];

  void Clear()
  {
    if(INVALID_HANDLE_VALUE != m_hFindVolume)
    {
      FindVolumeClose(m_hFindVolume);
      m_hFindVolume = INVALID_HANDLE_VALUE ;
    }
    m_szErrMsg[0]= _T('\0');
  }
  
  void GetErrorDetails()
  {
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), m_szErrMsg, ERRBUFSIZE, NULL );
  }

public:

  inline CVolumeEnumerator(void)
  {
    m_hFindVolume = INVALID_HANDLE_VALUE ;
    m_szErrMsg[0] = _T('\0');
  }

  inline ~CVolumeEnumerator(void)
  {
    Clear();
  }
    
  inline LPCTSTR GetFirstVolumeName()
  {
    Clear();

    if(INVALID_HANDLE_VALUE ==( m_hFindVolume = FindFirstVolume(m_szVolumeName, BUFSIZE)))
    {
      GetErrorDetails();
      return NULL;
    }

    return m_szVolumeName;
  }

  inline LPCTSTR GetNextVolumeName()
  {
    if(!FindNextVolume(m_hFindVolume, m_szVolumeName, BUFSIZE))
    {
      GetErrorDetails();
      return NULL;
    }

    return m_szVolumeName;
  }

  inline LPCTSTR GetLastErrorMessage() const {	return m_szErrMsg;	}
};

By   

P.GopalaKrishna

Homepage     Other Articles