Hello, I was doing some research on enumerating the different drives on a system, and I found some code on MSDN.
Here is the page:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364975%28v=vs.85%29.aspx

The source code looks like this:

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;
        }
} 

I modified the code to look like this, because I prefer to use ANSI operations:

#include <windows.h>
#include <stdio.h>
using namespace std;

int main(){

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

    if (dwResult > 0 && dwResult <= MAX_PATH)
    {
        char* szSingleDrive = szLogicalDrives;
            while(*szSingleDrive)
            {
                printf("Drive: %s\n", szSingleDrive);
                //printf only prints up to the first \0 character. 

                //get the next drive
                szSingleDrive += strlen(szSingleDrive) + 1;
                //strlen() only reads up to the first \0 character
                //so szSingleDrive always points to the beginning of a string. 
            }
    }
    system("pause");
}

I was wondering, how does this work:

while(*szSingleDrive)

I am not sure what the while operation is doing, I am guessing however that the pointer in the while loop is always pointing to string data, until it iterates on the final drive, and hits another \0 character, which causes the while test to be false. I am not sure, however so I thought I would ask somebody online.

Recommended Answers

All 2 Replies

I am guessing however that the pointer in the while loop is always pointing to string data, until it
iterates on the final drive, and hits another \0 character, which causes the while test to be false.

Good guess. However, there's a bit of a trick here because the pointer you're using points to potentially multiple strings pasted next to each other. For example, the string might be: "C:\0D:\0E:\0\0". So what happens is the body of the loop will use strlen() + 1 to push the pointer over the first null character. When it reaches the extra null character at the end, the loop stops for the reason you guessed. But it won't stop on the previous null characters because of stepping the pointer by strlen() + 1 characters.

Thank you, what you said more accurately reflects what I tried to express what I thought was happening (If that makes any sense).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.