GetLogicalDriveStrings()和char - 我在哪里做错了

hig*_*141 4 c++ msdn const-char char

我想搜索可能存在的任何驱动器,如C文件:\ d:\等使用GetLogicalDriveStrings,我可以能够得到驱动器的列表,但是当我添加任何额外的输出,我得到一个null在输出提示.这是我的代码:

#include "StdAfx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>

// Buffer length
DWORD mydrives = 100;
// Buffer for drive string storage
char lpBuffer[100];
const char *extFile = "text.ext";

// You may want to try the wmain() version
int main(void)
{
    DWORD test;
    int i;
    test = GetLogicalDriveStrings(mydrives, (LPWSTR)lpBuffer);
    if(test != 0)
    {
        printf("GetLogicalDriveStrings() return value: %d, Error (if any): %d \n", test, GetLastError());
        printf("The logical drives of this machine are:\n");
        // Check up to 100 drives...
        for(i = 0; i<100; i++)
        printf("%c%s", lpBuffer[i],extFile);
        printf("\n");
    }
    else
        printf("GetLogicalDriveStrings() is failed lor!!! Error code: %d\n", GetLastError());
    _getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想要上面的输出,C:\text.ext D:\text.ext ...而不是我text.ext只得到.我在用Microsoft Visual C++ 2010 Express

Jon*_*ter 7

GetLogicalDriveStrings()返回以null结尾的空终止字符串列表.例如,假设您的机器中有A,B和C驱动器.返回的字符串如下所示:

A:\<nul>B:\<nul>C:\<nul><nul>

您可以使用以下代码迭代返回缓冲区中的字符串并依次打印每个字符串:

DWORD dwSize = MAX_PATH;
char szLogicalDrives[MAX_PATH] = {0};
DWORD dwResult = GetLogicalDriveStrings(dwSize,szLogicalDrives);

if (dwResult > 0 && dwResult <= MAX_PATH)
{
    char* szSingleDrive = szLogicalDrives;
    while(*szSingleDrive)
    {
        printf("Drive: %s\n", szSingleDrive);

        // get the next drive
        szSingleDrive += strlen(szSingleDrive) + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,通过阅读文档可以找到函数如何工作的详细信息,包括我无耻地复制和粘贴的示例代码.