Carlos Ruben
Carlos Ruben

Reputation: 1

How to properly check if a registry key exists with c++?

My goal is very simple, I just want to check if a registry key exists or not with C++. I couldn't find anything useful online. The following code compiles with no errors but I get the output "Not opened", and I know I have that registry key.

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
using namespace std;
int main(){
    HKEY hKey;
    if(RegOpenKey(HKEY_LOCAL_MACHINE,TEXT("Software\\Oracle\\VirtualBox"),&hKey) == ERROR_SUCCESS)    {

        cout << "Opened";
    }
    else
    {
        cout << "not opened";
    }
    return 0;
}

Upvotes: 0

Views: 2532

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595837

The code you have is fine (though you should be using RegOpenKeyEx() instead, as RegOpenKey() is deprecated and provided only for backwards compatibility with 16bit code). You just need to pay attention to the return value. If RegOpenKey/Ex() returns either ERROR_PATH_NOT_FOUND or ERROR_FILE_NOT_FOUND, then the key does not exist. Any other return value means the key exists, and if the return value is ERROR_SUCCESS then you need to close the opened key, otherwise you don't have access to open the key even though it exists.

Upvotes: 2

Related Questions