-
RegSetValueEx
I am trying to modify the windows registry PATH with the following code. When I get to the RegSetValueEx, it bombs out and can't figure out why. When I display the error code it is a '5' but when I look in Winerror.h they are displayed in hex and decimal. 1) does anybody see anything wrong with the RegSetValueEx call and 2) how can I display the return code in a readable format as in Winerror.h
Code:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <tchar.h>
#include <iostream>
#include <string.h>
int checkKey(HKEY tree, const char *folder, char *key) {
long lRet,Rval;
HKEY hKey;
char temp[10000];
DWORD dwBufLen;
// Open location
lRet = RegOpenKeyEx( tree, folder, 0, KEY_QUERY_VALUE, &hKey );
if (lRet != ERROR_SUCCESS)
return 0;
// Get key
dwBufLen = sizeof(temp);
lRet = RegQueryValueEx( hKey, key, NULL, NULL, (BYTE*)&temp, &dwBufLen );
if (lRet != ERROR_SUCCESS)
return 0;
// Append to the Path
strcat(temp, ";c:instantclient");
dwBufLen = sizeof(temp);
//Update Key
Rval = RegSetValueEx(hKey,key,NULL,REG_EXPAND_SZ,(LPBYTE)temp,strlen(temp));
if (Rval != ERROR_SUCCESS)
{
printf("set error: %ld\n",Rval);
}
// Close key
lRet = RegCloseKey( hKey );
if (lRet != ERROR_SUCCESS)
return 0;
// Got this far, then key exists
return 1;
}
// This is the entry point for this application
int _tmain(void)
{
printf("Checking for key: HKEY_LOCAL_MACHINE -> SYSTEM -> CurrentControlSet -> Control -> Session Manager -> Environment -> Path\n");
if (checkKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "Path"))
printf("Key Exists.\n");
else
printf("Key Does Not Exist.\n");
return 0;
}
Thanks!
-
Error 5 is an access denial, Windows is saying you do not have sufficient permissions to do what you are doing.
It's late now, I'll look at it in the morning.
-
Welcome to the forums!
Here is a list of Win32 error codes.
You are getting the dreaded ERROR_ACCESS_DENIED because, when you open the key, you only request the KEY_QUERY_VALUE right. If you want to set a value, you need to combine this with the KEY_SET_VALUE right:
Code:
lRet = RegOpenKeyEx( tree, folder, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey );
You will need to be logged on as an administrator to modify most keys or values under HKEY_LOCAL_MACHINE. If you wanted to change an environment variable for the current user only, you could look under HKEY_CURRENT_USER\Environment.
On another matter, you should include the nul terminator when you write out a string to the registry:
Code:
Rval = RegSetValueEx(hKey,key,NULL,REG_EXPAND_SZ,(LPBYTE) temp,strlen(temp) + 1);
Finally, you are retrieving and modifying the path string in ansi (char) rather than unicode (wchar_t). If the original path string contained unicode characters, they may be lost.
-
Works like a charm! Thanks!!!!!
-
Cheers anon, I was just going to look at this one! I'll do somebody elses now!