WinApi:无法读取注册表

时间:2018-01-28 20:41:06

标签: c++ winapi

我试图使用winapi和c ++读取注册表。

代码运行,但结果不是注册表的内容 在hexdump之后只有0xCD一遍又一遍地重复。 (所以,好像数据还没有被RegQueryValueEx修改,而且只是malloc的结果) 我也尝试以管理员身份运行,没有运气。

这是我使用的代码:

HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\Shell\\Bags\\1\\Desktop", 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
    return;

//Read & save
DWORD BufferSize = TOTALBYTES;
DWORD cbData;
DWORD dwRet;

LPBYTE data = (LPBYTE)malloc(BufferSize);
cbData = BufferSize;

DWORD type = REG_BINARY;

dwRet = RegQueryValueEx(hKey, "IconLayouts", NULL, &type, data, &cbData);

while (dwRet == ERROR_MORE_DATA) {

    BufferSize += BYTEINCREMENT;
    data = (LPBYTE)realloc(data, BufferSize);
    cbData = BufferSize;

    dwRet = RegQueryValueEx(hKey, "IconLayouts", NULL, &type, data, &cbData);
}

if (dwRet == ERROR_SUCCESS)
{
    //Write current registry to a file
    std::ofstream currentRegistryFile(DIRECTORY + currentDesktop + ".bin");
    if (!currentRegistryFile) {
        log(currentDesktop + " file couldn't be opened.");
        return;
    }
    for (int i = 0; i < cbData; i++)
        currentRegistryFile << (data)[cbData];
}
else
    log("Couldnt read registry");


//Close registry
RegCloseKey(hKey);

1 个答案:

答案 0 :(得分:1)

您的保存代码就是问题所在。它实际上是超出界限访问数组:

for (int i = 0; i < cbData; i++)
    currentRegistryFile << (data)[cbData];

请注意,您使用data的常量值而不是循环变量cbData索引i。改变这一点。

相关问题