Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c++ - GetLogicalDriveStrings() and char - Where am I doing wrongly

I want to search a file which may be present in any drives such as C:, D: etc. Using GetLogicalDriveStrings I can able to get the list of drives but when I add anything extra for the output, I am getting a null in the output prompt. Here is my code:

#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 
", test, GetLastError());
        printf("The logical drives of this machine are:
");
        // Check up to 100 drives...
        for(i = 0; i<100; i++)
        printf("%c%s", lpBuffer[i],extFile);
        printf("
");
    }
    else
        printf("GetLogicalDriveStrings() is failed lor!!! Error code: %d
", GetLastError());
    _getch();
    return 0;
}

I want above output as C:ext.ext D:ext.ext ... rather I am getting text.ext only. I am using Microsoft Visual C++ 2010 Express

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

GetLogicalDriveStrings() returns a double-null terminated list of null-terminated strings. E.g., say you had drives A, B and C in your machine. The returned string would look like this:

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

You can use the following code to iterate through the strings in the returned buffer and print each one in turn:

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
", szSingleDrive);

        // get the next drive
        szSingleDrive += strlen(szSingleDrive) + 1;
    }
}

Note that the details of how the function works, including the example code that I shamelessly copied and pasted, can be found by reading the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...