Search code examples
c++registry

How to check if the (default) value has not been set in the registry


I need to check if the (default) value has not been set in the registry using C++. Whenever the value has not been set and I try to access the value, the program crashes, and I don't know how to check if the value has been set. Here is the code:

DWORD valueLength = 256;
char* value = new char[valueLength];
auto queryValueErrorCode = RegQueryValueEx(key, NULL, NULL, NULL, (LPBYTE) value,
        &valueLength);
while(queryValueErrorCode == ERROR_MORE_DATA) {
    valueLength += 256;
    char* newValue = new char[valueLength];
    delete[] value;
    value = newValue;
    queryValueErrorCode = RegQueryValueEx(key, NULL, NULL, NULL, (LPBYTE) newValue,
            &valueLength);
}

This code doesn't crash by itself - when I try to access the value is when it crashes, so I have to check if the value has been set or not.


Solution

  • The (default) value does not exist until it has been set, so check the error code for

    ERROR_FILE_NOT_FOUND
    

    before trying to access the value.