user1575008
user1575008

Reputation: 11

RegEnumKeyEx doesn't work properly

I'm trying make a function that lists all subkeys of a specific (windows registry) key.

What's happening is that only the 1st item is outputted correctly, all the others are truncated or repeated - I think it's a buffer issue.

I've already read the function documentation, but it hasn't helped me much.

Here's the code:

#include<stdio.h>
#include<windows.h>

void print_list(HKEY hkey, char* path){

char dwValue[255];
DWORD  dwSize = 0;
DWORD n; // subkeys
HKEY tmp;
int i;

if(RegOpenKeyEx(hkey, path, 0, KEY_READ, &tmp) == ERROR_SUCCESS){

    DWORD  dwSize = sizeof(dwValue);

    RegQueryInfoKey(tmp,NULL,NULL,NULL,&n,NULL,NULL,NULL,NULL,NULL,NULL,NULL);      

    for(i=0; i< n; i++){
        RegEnumKeyEx(tmp,i,dwValue,&dwSize,NULL,NULL,NULL,NULL);
        printf("%s\n", dwValue);
    }

    RegCloseKey(tmp);
}
}

int main(){
print_list(HKEY_LOCAL_MACHINE, "SOFTWARE");
return 0;
}

Upvotes: 0

Views: 5618

Answers (2)

hmjd
hmjd

Reputation: 121971

Add the following line to before the call to RegEnumKeyEx():

dwSize = sizeof(dwValue);

as dwSize is both an input and output parameter. On input it states the size of the buffer. From RegEnumKeyEx():

A pointer to a variable that specifies the size of the buffer specified by the lpName parameter, in characters. This size should include the terminating null character. If the function succeeds, the variable pointed to by lpcName contains the number of characters stored in the buffer, not including the terminating null character.

Note, you should always check return values from functions (like you have done for RegOpenKeyEx()).

Upvotes: 3

Adrian McCarthy
Adrian McCarthy

Reputation: 47962

If you check the return code from the RegEnumKeyEx call, you'll see that you're getting 0xEA, which means that the data is longer than the buffer you've provided.

This is happening because dwSize is an input/output parameter. When you call it, the function assumes that the buffer has at last dwSize characters available. When it returns, dwSize has been changed to the size of the actual data. This leaves dwSize much smaller than the actual buffer size. On the next call, it might not think you have enough space, and it returns the error code instead.

You need to reset dwSize before each call.

Upvotes: 1

Related Questions