Tom
Tom

Reputation: 9643

c++ simple reading from registry problem

platform- win.

Well i'm trying to get a value of a key named SunJavaUpdateSched but i'm getting an error. i'm getting the second error, somehow i can open the key but can't get the value. So this is the code so far:

void dealWithRegistry()
{
 HKEY regkey1;
 char data[100];
 DWORD datasize = sizeof (data) / sizeof (char);
 LONG rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &regkey1);
 if (rc != ERROR_SUCCESS)
 {
  cout << "there was a problem openning" << endl;
 }
 else
 {
  rc = RegGetValue (regkey1, NULL, L"SunJavaUpdateSched", RRF_RT_REG_SZ, NULL, (void*) data, &datasize);
  if (rc != ERROR_SUCCESS)
  {
  cout << "there was a problem getting the value" << endl;
  }
 }

 printf("%s\n", data);

}

Upvotes: 0

Views: 908

Answers (2)

atzz
atzz

Reputation: 18010

  1. ERROR_MORE_DATA indicates that your data buffer is not big enought to receive the value. See the example in the MSDN article on RegQueryValueEx for a recipe on how to allocate the buffer correctly.

  2. Your use of L"..." literals suggests that your project is compiled as Unicode, which means that char data[] has to be WCHAR data[] (or TCHAR data[]).

  3. The expression sizeof (data) / sizeof (char) should be written as sizeof (data) / sizeof (data[0]); this way it will stay correct regardless of the actual type with which data is declared. Also, MSVC standard library has a (nonstandard) macro _countof exactly for this purpose.

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106539

Print out the actual error value. You can look up the system error code which will tell you exactly what the problem is.

Note that RegGetValue is going to return a wide character string, not a character string, which means your variable using chars is going to give you garbage.

Couple issues with the code itself:

  1. dealWithRegistry ... really? How about ReadJavaUpdateSchedulerValue?
  2. sizeof(char) is always 1 (by definition).
  3. In C++ you should be using static_cast here instead of the C style cast.
  4. You aren't calling RegCloseKey anywhere!

Upvotes: 2

Related Questions