我想使用VC++在Windows中列出所有可用的驱动器字母(尚未使用)。
我该怎么做?
::GetLogicalDrives() 返回一个掩码形式表示可用(已使用)驱动器的列表。这应该包括映射网络驱动器。因此,您可以简单地遍历位以查找值为零的位,表示未连接任何驱动器。如果不确定,您可以始终调用::GetDriveType() 并传入驱动器号+":\"
(":\\"
在C代码中,或者当然是Unicode支持的术语中的_T(":\\")
),这将返回DRIVE_UNKNOWN
或DRIVE_NO_ROOT_DIR
如果驱动器可用。
我不确定如何枚举它们,或者是否会在Visual C ++上编译,但我在Dev C ++或Code Blocks上进行了编码以检查哪些驱动器可以通过CreateFile访问,并使用GetDriveType确定驱动器类型。该程序从A到Z检查驱动器:
#include <windows.h>
#include <cstring>
#include <sstream>
#include <iostream>
using namespace std;
int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, INT nShowCmd)
{
HANDLE hDevice = NULL;
HANDLE fileFind = NULL;
while(true)
{
Sleep(3005);
char drv='A';
while(drv!='[')
{
Sleep(105);
const char *charDrvCF;
const char *charDrv;
stringstream Str;
string drvStr;
Str<<drv;
Str>>drvStr;
string drvSpc=drvStr+":\\";
string fCheck="\\\\.\\";
string fhCheck=fCheck+drvStr+":";
charDrvCF=fhCheck.c_str();
charDrv=drvSpc.c_str();
hDevice=CreateFile(charDrvCF,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if(hDevice!=INVALID_HANDLE_VALUE)
{
switch(GetDriveType(charDrv))
{
case DRIVE_FIXED:
{
cout<<"Fixed drive detected: "<<charDrv<<endl;
break;
}
case DRIVE_REMOVABLE:
{
cout<<"Removable drive detected: "<<charDrv<<endl;
break;
}
case DRIVE_NO_ROOT_DIR:
{
cout<<"There is no volume mounted at the specified path. "<<charDrv<<endl;
break;
}
case DRIVE_REMOTE:
{
cout<<"The drive is a remote (network) drive. "<<charDrv<<endl;
break;
}
case DRIVE_CDROM:
{
cout<<"The drive is a CD-ROM drive. "<<charDrv<<endl;
break;
}
case DRIVE_RAMDISK:
{
cout<<"The drive is a RAM disk. "<<charDrv<<endl;
break;
}
case DRIVE_UNKNOWN:
{
cout<<"The drive type cannot be determined. "<<charDrv<<endl;
break;
}
}
}
drv++;
}
}
}
std::vector<std::string> getListOfDrives() {
std::vector<std::string> arrayOfDrives;
char* szDrives = new char[MAX_PATH]();
if (GetLogicalDriveStringsA(MAX_PATH, szDrives));
for (int i = 0; i < 100; i += 4)
if (szDrives[i] != (char)0)
arrayOfDrives.push_back(std::string{szDrives[i],szDrives[i+1],szDrives[i+2]});
delete[] szDrives;
return arrayOfDrives;
}
返回一个磁盘向量,例如 C:\D:\E:\F:\
std::vector<std::string> drives = getListOfDrives();
for (std::string currentDrive : drives) {
std::cout << currentDrive << std::endl;
}
GetLogicalDrives和GetLogicalDriveStrings不能识别在不同命名空间中创建的网络驱动器。
例如,在本地系统下运行的服务调用这些函数将无法看到由已登录用户创建的网络驱动器。
这种情况始于Windows XP。以下文章描述了这种情况: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363908(v=vs.85).aspx
for (w_chDrv = 'C'; w_chDrv <= 'Z'; w_chDrv++)
{
// make root path
_stprintf_s(w_szRootPath, 3, _T("%c:"), w_chDrv);
// get driver type
w_nDriverType = GetDriveType(w_szRootPath);
if ((w_nDriverType != DRIVE_REMOVABLE) && (w_nDriverType != DRIVE_FIXED))
continue;
// if you got here that means w_szRootPath is a valid drive
}