views:

39

answers:

3

I need to grab the path from the registry. The following code works except for the last part where I'm storing the path to the string. Running the debugger in Visual Studio 2008 the char array has the path, but every other character is a zero. This results in the string only being assigned the first letter. I've tried changing char res[1024] to char *res = new char[1024] and this just makes it store the first letter in the char array instead of the string. The rest of the program needs the path as a string datatype so it can't stay as a char array. What am I missing here?

unsigned long type=REG_SZ, size=1024;
string path;
char res[1024];
HKEY key;

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Classes\\dsn\\shell\\open\\command"), NULL, KEY_READ, &key)==ERROR_SUCCESS){

    RegQueryValueEx(key,
    NULL,// YOUR value
    NULL,
    &type,
    (LPBYTE)res,
    &size);
    RegCloseKey(key);

    path = string(res);
}
A: 

You are compiling in Unicode. Go to Project Settings>Configuration Properties>General and change "Character Set" to "Not Set", and rebuild your project.

RegOpenKey is actually a macro defined in the WINAPI headers. If Unicode is enabled, it resolves to RegOpenKeyW, if not then it resolves to RegOpenKeyA. If you want to continue to compile under unicode, then you can just call RetgOpenKeyA directly instead of using the macro.

Otherwise, you'll need to deal with Unicode strings which, if needed, we can help you with also.

John Dibling
Could also change the char array to `TCHAR`, `string` to `wstring`
Steve Townsend
+2  A: 

You're getting back a Unicode string, but assigning it to a char-based string.

You could switch path's class to being a 'tstring' or 'wstring', or use RegQueryValueExA (A for ASCII).

Graham Perks
RegQueryValueExA worked best. Thanks!
alex
@alex - in general, it's not a good idea to use the charset-specific xxxA and xxxW APIs. Better to stick with the original code (i.e. the API name used in the Microsoft docs) and switch your compiler setting per @John Dibling's answer. imo understanding how this works is more useful to you than fixing this one registry read issue.
Steve Townsend
You're probably right, Steve, but since the code snippet is going into a larger program that someone else wrote (who has it set to multi-byte), this worked better than fixing the larger program to accommodate a not-set charset.
alex
A: 

For C++, you may prefer to access the Registry using the ATL helper class CRegKey. The method for storing string values is QueryStringValue. There are other (somewhat) typesafe methods for retrieving and setting different registry value types.

It's not the best C++ interface (eg. no std::string support) but a little smoother than native Win32.

Steve Townsend