我对WIN32 C++非常陌生。我要做的是使用GetDriveType函数动态定义每个驱动器的类型。
这是我的密码
#include Windows.h
#include stdio.h
#include iostream
using namespace std;
int main()
{
// Initial Dummy drive
WCHAR myDrives[] = L" A";
// Get the logical drive bitmask (1st drive at bit position 0, 2nd drive at bit position 1... so on)
DWORD myDrivesBitMask = GetLogicalDrives();
// Verifying the returned drive mask
if(myDrivesBitMask == 0)
wprintf(L"GetLogicalDrives() failed with error code: %d\n", GetLastError());
else {
wprintf(L"This machine has the following logical drives:\n");
while(myDrivesBitMask) {
// Use the bitwise AND with 1 to identify
// whether there is a drive present or not.
if(myDrivesBitMask & 1) {
// Printing out the available drives
wprintf(L"drive %s\n", myDrives);
}
// increment counter for the next available drive.
myDrives[1]++;
// shift the bitmask binary right
myDrivesBitMask >>= 1;
}
wprintf(L"\n");
}
system("pause");
}但是GetDriveType(myDrives)继续返回值1,即“无根目录”。如果我使用“喜欢”( like GetDriveType("C:\\") ),它会显示正确的结果。我如何解决这个问题?任何帮助都将不胜感激。
谢谢
发布于 2014-09-14 04:07:57
您在myDrives中有一个领先的空间。GetDriveType()不会忽略前导空格。删除它,您的代码将工作。参见下面的工作示例:
#include <Windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
// Initial Dummy drive
WCHAR myDrives[] = L"A:\\";
// Get the logical drive bitmask (1st drive at bit position 0, 2nd drive at bit position 1... so on)
DWORD myDrivesBitMask = GetLogicalDrives();
// Verifying the returned drive mask
if (myDrivesBitMask == 0)
wprintf(L"GetLogicalDrives() failed with error code: %d\n", GetLastError());
else {
wprintf(L"This machine has the following logical drives:\n");
while (myDrivesBitMask) {
// Use the bitwise AND with 1 to identify
// whether there is a drive present or not.
if (myDrivesBitMask & 1) {
// Printing out the available drives
wprintf(L"drive %s -type = %d\n", myDrives, GetDriveType(myDrives));
}
// increment counter for the next available drive.
myDrives[0]++;
// shift the bitmask binary right
myDrivesBitMask >>= 1;
}
wprintf(L"\n");
}
system("pause");
}发布于 2014-09-14 04:11:52
您的myDrive[]初始化数据有两个问题。它在驱动器字母之前有一个额外的空间,并且它没有在驱动器字母之后指定冒号-反斜杠。GetDriveType()文档明确提到:
lpRootPathName in,可选 驱动器的根目录。尾随反斜杠是必需的。如果此参数为NULL,则函数使用当前目录的根目录。
您应该修改myDrives的声明如下:
// Initial Dummy drive
WCHAR myDrives[] = L"A:\\"; 然后,您可以按如下方式增加循环中的驱动器号:
// increment counter for the next available drive.
myDrives[0]++; https://stackoverflow.com/questions/25829931
复制相似问题