如何在Visual C ++中读取多行多字符串注册表项?

时间:2014-10-28 04:09:22

标签: winapi visual-c++ mfc registry

我正在使用Visual Studio 2008.我在vc ++ mfc应用程序中工作 我想知道如何从注册表中读取多行字符串值.Here类型REG_MULTI_SZ表示一系列以空字符结尾的字符串,以空字符串(\ 0)结尾。
到目前为止,我只能阅读第一行。给我一个关于如何一次读取多串的想法 谢谢 enter image description here

我试过像这样的东西

HKEY hKey;
CString RegPath = _T("SOFTWARE\\...\\...\\");   //Path
if(ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,RegPath,0,KEY_READ|KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE | KEY_WOW64_64KEY,&hKey))
{
    DWORD nBytes,dwType = REG_MULTI_SZ;
    CString version;
    if(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,&dwType,0,&nBytes))
    {
        ASSERT(REG_MULTI_SZ == dwType);
        LPTSTR buffer = version.GetBuffer(nBytes/sizeof(TCHAR));
        VERIFY(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,0,(LPBYTE)buffer,&nBytes));
        AfxMessageBox(buffer);     //Displaying Only First Line
        version.ReleaseBuffer();
    }
::RegCloseKey(hKey);
}

1 个答案:

答案 0 :(得分:1)

假设您的多字符串由两个字符串“AB”和“CD”组成。

内存中的布局如下:

+--------+
|  'A'   |   <-- buffer  // first string
+--------+
|  'B'   |
+--------+
|   0    |    // terminator of first string
+--------+
|  'C'   |    // second string
+--------+
|  'D'   |
+--------+
|   0    |    // terminator of second string
+--------+
|   0    |    // terminator of multi string
+--------+

因此AfxMessageBox(buffer)仅显示第一个字符串。

您不应将多字符串读入CString,因为CString仅处理nul终止字符串。您应该将多字符串读入TCHAR缓冲区,然后解析该缓冲区以提取单个字符串。

基本上:

 ASSERT(REG_MULTI_SZ == dwType);
 LPTSTR buffer = new TCHAR[nBytes / sizeof(TCHAR)];
 VERIFY(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,0,(LPBYTE)buffer,&nBytes));

 CStringArray strings;
 const TCHAR *p = buffer;
 while (*p)               // while not at the end of strings
 {
   strings.Add(p);        // add string to array
   p += _tcslen(p) + 1 ;  // find next string
 }

 delete [] buffer;

 // display all strings (for debug and demonstration purpose)
 for (int i = 0; i < strings.GetCount(); i++)
 {
   AfxMessageBox(strings[i]);
 }

 // now the strings array contains all strings