返回驱动器号列表的程序

Program that returns a list of drive letters

本文关键字:程序 列表 驱动器 返回      更新时间:2023-10-16

在我的计算机示例中,所需的输出应该是:"C: E: F: H: N:" .我知道这是可能的,但最简单的方法是什么?Pottering in QueryDosDevice 输出

#ifndef UNICODE
#define UNICODE
#endif

#include <Windows.h>
#include <fstream>
#include <iostream>
const int REPORT_LENGTH = 5000;
int main(void)
{
    TCHAR targetPath[REPORT_LENGTH];
    std::ofstream oFile;
    oFile.open("dos device query.txt");
    QueryDosDevice(NULL,targetPath,REPORT_LENGTH);
    for(int i=0; i<REPORT_LENGTH;i++)
    if (targetPath[i]=='')(targetPath[i]='n');

    for(int i=0; i<REPORT_LENGTH; i++)
    oFile<<static_cast<char>(targetPath[i]);
    oFile.close();
    return 0;
}

这将是对时间和资源的巨大浪费。此外,函数GetLogicalDriveStrings背叛了我很多。

#include <Windows.h>
int main()
{
    TCHAR buffer[50];
    GetLogicalDriveStrings(50,buffer);
    MessageBox(0,buffer,"Drives in the system",MB_OK); 

    return 0;
}

它只显示"C:\"伏柳胺。

带有 GetLogicalDrives 的示例,尽管不是连接到字符串(作为练习留给 OP 和读者;)(:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
int __cdecl _tmain(int argc, _TCHAR *argv[])
{
    // Get the bit mask of drive letters
    DWORD drives = ::GetLogicalDrives();
    // Go through all possible letters from a to z
    for(int i = 0; i < 26; i++)
    {
        // Check if the respective bit is set
        if(drives & (1 << i))
        {
            // ... and if so, print it
            _tprintf(TEXT("Drive %c: existsn"), _T('A') + i);
        }
    }
    return 0;
}
GetLogicalDriveStrings()

要走的路,你只需要正确使用。 您假设它返回一个包含所有驱动器字符串的字符串,但事实并非如此。 它返回一个字符串数组,每个驱动器一个,因此您必须遍历数组:

#include <windows.h> 
int main() 
{ 
    TCHAR buffer[(4*26)+1] = {0}; 
    GetLogicalDriveStrings(sizeof(buffer) / sizeof(TCHAR), buffer); 
    for (LPTSTR lpDrive = buffer; *lpDrive != 0; lpDrive += 4)
        MessageBox(NULL, lpDrive, "Drive in the system", MB_OK);
    return 0; 
}