动态使用GetDriveType
Dynamically using GetDriveType
本文关键字:GetDriveType 动态 更新时间:2023-10-16
我是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: %dn", 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 %sn", 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,即"无根目录"。如果我像GetDriveType("C:\")
一样使用,它会显示正确的结果。我该如何解决这个问题?如有任何帮助,我们将不胜感激。
感谢
您的myDrive[]
初始化数据有两个问题。它在驱动器号之前有一个额外的空间,并且没有在驱动器号之后指定冒号反斜杠。GetDriveType()的文档中明确提到:
lpRootPathName[in,可选]
驱动器的根目录A尾部反斜杠是必需的如果此参数为NULL,则函数使用当前目录的根目录。
您应该修改myDrives
的声明如下:
// Initial Dummy drive
WCHAR myDrives[] = L"A:\";
然后你可以在循环中增加驱动器号,如下所示:
// increment counter for the next available drive.
myDrives[0]++;
您在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: %dn", 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 = %dn", myDrives, GetDriveType(myDrives));
}
// increment counter for the next available drive.
myDrives[0]++;
// shift the bitmask binary right
myDrivesBitMask >>= 1;
}
wprintf(L"n");
}
system("pause");
}
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- 视觉studo 2019中的漫画和静态/动态绑定
- 从C++中的数字输入动态创建矩阵
- 如何从QToolBox中动态创建的QLineEdit中获取文本
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 动态使用GetDriveType