读取std :: string的注册表键值的最简单方法是什么?

Mac*_*iek 6 c++ registry

读取std :: String的注册表键值的最简单方法是什么?

说我有:

HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value1 = "some text"
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value2 = "some more text"
Run Code Online (Sandbox Code Playgroud)

如何快速将这些值传递给std :: string?

Yac*_*oby 9

我有一些非常古老的代码,但它应该给你一个好主意:

/**
* @param location The location of the registry key. For example "Software\\Bethesda Softworks\\Morrowind"
* @param name the name of the registry key, for example "Installed Path"
* @return the value of the key or an empty string if an error occured.
*/
std::string getRegKey(const std::string& location, const std::string& name){
    HKEY key;
    TCHAR value[1024]; 
    DWORD bufLen = 1024*sizeof(TCHAR);
    long ret;
    ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, location.c_str(), 0, KEY_QUERY_VALUE, &key);
    if( ret != ERROR_SUCCESS ){
        return std::string();
    }
    ret = RegQueryValueExA(key, name.c_str(), 0, 0, (LPBYTE) value, &bufLen);
    RegCloseKey(key);
    if ( (ret != ERROR_SUCCESS) || (bufLen > 1024*sizeof(TCHAR)) ){
        return std::string();
    }
    std::string stringValue = std::string(value, (size_t)bufLen - 1);
    size_t i = stringValue.length();
    while( i > 0 && stringValue[i-1] == '\0' ){
        --i;
    }
    return stringValue.substr(0,i); 
}
Run Code Online (Sandbox Code Playgroud)

  • 此代码可能不安全.RegQueryValueEx文档(http://msdn.microsoft.com/en-us/library/ms724911(VS.85).aspx)说(在"备注"部分中)检索到的字符串可能不会以空值终止.更进一步,如果它是一个"多字符串",它将有一个双空终止符,这也将被这个代码错误处理. (9认同)