我正在使用此功能:GetLogicalDriveStringsW(ARRAYSIZE(myDrives) - 1, myDrives)
然后我循环遍历所有检索到的驱动器。
char driveLetter;
UINT driveType;
WCHAR myDrives[105];
for (LPWSTR drive = myDrives; *drive != 0; drive += 4)
{
driveType = GetDriveTypeW(drive);
if (driveType == DRIVE_CDROM)
{
**driveLetter = // (drive) Need just the drive character**
}
}
在使用上述功能时如何获取驱动器字符的任何想法?
答案 0 :(得分:3)
驱动器号都是纯ASCII,这意味着它们与char
和wchar_t
具有完全相同的值。
答案 1 :(得分:3)
驱动器号始终位于A..Z范围内,在Windows上,当您处理ASCII范围内的字符时,您可以使用简单的转换从WCHAR
转换为char
:< / p>
const WCHAR* somepath = L"c:\\foo";
char driveletter;
driveletter = (char) *somepath;
printf("letter: %c\n", driveletter);
这在Windows上是安全的,因为WCHAR
编码为UTF-16LE,而char
/ CHAR
编码的代码页是ASCII的超集。您无法对其他平台上的char
和wchar_t
做出相同的假设。
我个人更喜欢使用GetLogicalDrives
而不是GetLogicalDriveStrings
:
char driveletter;
WCHAR rootpath[] = L"?:\\";
DWORD validdrives = GetLogicalDrives();
for (UINT i = 0; i < 26; ++i)
{
if (validdrives & (1 << i))
{
driveletter = 'A' + i;
rootpath[0] = driveletter;
UINT drivetype = GetDriveTypeW(rootpath);
printf("Drive %c (%ls) is type %u\n", driveletter, rootpath, drivetype);
if (drivetype == DRIVE_CDROM)
{
printf("CD-Rom drive letter %c\n", driveletter);
}
}
}
答案 2 :(得分:2)
只需调用GetLogicalDriveStrings()
和GetDriveType()
的Ansi版本,而不是Unicode版本:
char driveLetter = 0;
CHAR myDrives[105] = {};
GetLogicalDriveStringsA(104, myDrives);
for (LPSTR drive = myDrives; *drive != 0; drive += 4) {
if (GetDriveTypeA(drive) == DRIVE_CDROM) {
driveLetter = *drive;
break;
}
}