Take the 2-minute tour ×

I've got most of the code for writing a value to the windows registry, however when I change the path to a dummy key and value that I've set up for testing it fails. My code is below:

    HKEY hKey;
    LPCTSTR sk = TEXT("SOFTWARE\TestSoftware");

    LONG openRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE, sk, 0, KEY_ALL_ACCESS , &hKey);

    if (openRes==ERROR_SUCCESS) {
    	printf("Success opening key.");
    } else {
    	printf("Error opening key.");

    LPCTSTR value = TEXT("TestSoftwareKey");
    LPCTSTR data = "TestData\0";

    LONG setRes = RegSetValueEx (hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data)+1);

    if (setRes == ERROR_SUCCESS) {
    	printf("Success writing to Registry.");
    } else {
    	printf("Error writing to Registry.");

    LONG closeOut = RegCloseKey(hKey);

    if (closeOut == ERROR_SUCCESS) {
    	printf("Success closing key.");
    } else {
    	printf("Error closing key.");

All three tests yield error statuses.

The part that confuses me is that I was able to run this code when pointing it at other portions of the registry. Any ideas?

thanks, brian

share|improve this question
Note that the RegSetValueEx function takes the string length in bytes (not characters) as its last argument. Therefore, you are better off using StringCbLength instead of strlen. –  Felix Dombek Jun 30 '11 at 8:34
add comment

1 Answer

up vote 20 down vote accepted

I feel silly. The solution is that need to properly escape the slash in the string as follows:

LPCTSTR sk = TEXT("SOFTWARE\\TestSoftware");

Hopefully someone finds this useful...

share|improve this answer
add comment

Your Answer


