2014-10-28 96 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