[WinAPI] Cum enumar drive-urile din sistem?

Folosire Windows API in programe C/C++ (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3778
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[WinAPI] Cum enumar drive-urile din sistem?

Post by Ovidiu Cucu » 01 Aug 2009, 09:27

Intrebare: Cum enumar drive-urile din sistem (partitii, discuri, drive-uri de retea, etc)?

Raspuns: Exista doua functii cu care se poate face aceasta: GetLogicalDrives si GetLogicalDriveStrings.

Exemple:

Folosind GetLogicalDrives intorc lista de drive-uri intr-un vector de char-uri.

Code: Select all

void EnumLogicalDrives(std::vector<char>& arrDrives) 
{ 
    arrDrives.clear(); 

    const DWORD dwDrivesMask = ::GetLogicalDrives(); 
    const DWORD dwMaxDrives = 26; 

    for(DWORD dwBit = 0; dwBit < dwMaxDrives; dwBit++) 
    { 
        if(dwDrivesMask & (1 << dwBit)) 
        { 
            arrDrives.push_back('A' + static_cast<char>(dwBit)); 
        } 
    } 
} 
Folosind GetLogicalDriveStrings intorc lista de drive-uri intr-un vector de string-uri:

Code: Select all

void EnumLogicalDrives(std::vector<std::string>& arrDrives) 
{ 
    arrDrives.clear(); 

    const DWORD nBufferLength = 105; // 26 * 4  +  1 
    char lpBuffer[nBufferLength]; 
    ::GetLogicalDriveStringsA(nBufferLength, lpBuffer); 
    char* pDrive = lpBuffer; 
    while(*pDrive) 
    { 
        std::string strDrive = pDrive; 
        arrDrives.push_back(strDrive); 
        pDrive += strDrive.length() + 1; 
    } 
} 
Un programel complet care listeaza la consola lista de drive-uri.

Code: Select all

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>

void EnumLogicalDrives(std::vector<std::string>& arrDrives);

int main()
{
   std::vector<std::string> arrDrives;
   EnumLogicalDrives(arrDrives);
   std::vector<std::string>::const_iterator end = arrDrives.end();
   std::vector<std::string>::iterator iter;
   for(iter = arrDrives.begin(); iter != end; ++iter)
   {
      std::cout << *iter << std::endl;
   }
   system("pause");
	return 0;
}

void EnumLogicalDrives(std::vector<std::string>& arrDrives) 
{ 
    arrDrives.clear(); 

    const DWORD nBufferLength = 105; // 26 * 4  +  1 
    char lpBuffer[nBufferLength]; 
    ::GetLogicalDriveStringsA(nBufferLength, lpBuffer); 
    char* pDrive = lpBuffer; 
    while(*pDrive) 
    { 
        std::string strDrive = pDrive; 
        arrDrives.push_back(strDrive); 
        pDrive += strDrive.length() + 1; 
    } 
} 

<< Back to Windows API Index



Post Reply