简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM