2014-10-28 95 views
-3

我正在使用Visual Studio 2008.我正在使用vC++ mfc应用程序。
我想知道如何从注册表中读取多行字符串值。这里的类型REG_MULTI_SZ指示由空字符串(\ 0)终止的以空字符结尾的字符串序列。
到目前为止,我只能阅读第一行。给我想法,我如何一次读取多个字符串。
感谢 enter image description here如何在Visual C++中读取多行多字符串注册表项?

我想这样的事情

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

显示你有什么到目前为止已经试过。然后,我们会更容易回答你的问题。 – 2014-10-28 08:36:02

回答

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 
+0

这就是我想知道的,如何找到下一个字符串?如你所示的例子,我怎样得到字符串'CD'。 – Himanshu 2014-10-28 09:48:17

+0

请参阅我编辑的答案。 – 2014-10-28 09:55:49

+0

对不起,但米仍然得到同样的结果。它只显示第一行。 – Himanshu 2014-10-28 10:02:59