Eugeny89
Eugeny89

Reputation: 3731

RegSetValueEx and CHAR

consider the following code

addHash("hash");

bool addHash(char* hash) {
    HKEY hKey = 0;
    int code = RegOpenKey(HKEY_CURRENT_USER, subkey, &hKey);

    const int length = strlen(hash)+1;
    WCHAR whash[100];
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, hash, strlen(hash), whash, 100);
    LONG setRes = RegSetValueEx(hKey, L"hash", 0, REG_SZ, (LPBYTE)whash, strlen(hash)+1);

    return true;
}

After code is compiled and executed "ha" is puted into registry. Can somebody tell me where the problem is?

Thank you in advance!

Upvotes: 0

Views: 1537

Answers (2)

LihO
LihO

Reputation: 42103

I think this is what you are trying to do:

#include <tchar.h>
#include <Windows.h>
using namespace std;

bool addHash(wstring hash) {
    const wchar_t* wHash = hash.c_str();
    LONG ret = RegSetKeyValue(HKEY_CURRENT_USER, _T("Software\\aa\\test"), _T("hash"), REG_SZ, wHash, hash.length() * sizeof(wchar_t));
    return (ret == ERROR_SUCCESS);
}

int main()
{
    addHash(_T("A42B2094EDC43"));
    return 0;
}

Hope this helps ;)

Upvotes: 1

hmjd
hmjd

Reputation: 122001

The last argument is the number of bytes, not the number of characters, that the second last argument points to.

So the first five bytes (strlen(hash) + 1) of whash will be stored in the registry. Change to:

LONG setRes = RegSetValueEx(hKey,
                            L"hash",
                            0,
                            REG_SZ,
                            (LPBYTE)whash,
                            (wcslen(whash) + 1) * sizeof(WCHAR));

You may also need to initialise whash (I don't think MultiByteToWideChar() adds a null terminator for you):

WCHAR whash[100] = { 0 };

Upvotes: 1

Related Questions