为什么我的注册表阅读程序失败了?

时间:2011-06-13 03:21:29

标签: c++ arrays string winapi registry

Regedit Screenshot http://i54.tinypic.com/3503vi8.jpg

现在,这段代码:

HKEY hKey;
LONG regOpenCriss = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", 0, KEY_QUERY_VALUE, &hKey);
char mydata[2000] = {'\0'};
DWORD dwType = REG_SZ;
DWORD dataLength = sizeof(mydata);
LPVOID messagecaliss;
GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL, GetLastError(), NULL,(LPTSTR) &messagecaliss, 0, NULL );

if (regOpenCriss == ERROR_SUCCESS) {
    RegQueryValueEx(hKey, "Test2", 0, &dwType, (LPBYTE)&mydata, &dataLength); //change the key you want to read
    printf("%s\n", mydata);
    system("PAUSE");
    RegCloseKey(hKey);
}
else
    MessageBox(NULL,(LPCTSTR)messagecaliss,"ERROR",MB_OK|MB_ICONINFORMATION);
printf("%s\t\n", mydata);
std::string FullPath(mydata,dataLength-1);
printf("%s\n", FullPath);
std::string FileName = GetFileNameFromPath(mydata);
printf("%s\n", FileName);
system("PAUSE");

函数GetFilenameFromPath定义为:

std::string GetFileNameFromPath (std::string str) {
size_t found;
found=str.find_last_of("/\\");
return str.substr(found+1);}

当我用“QKSMTPServer3”作为第二个参数调用RegQueryValueEx时,这是输出:

C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
Press any key to continue . . .
C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
QKSmtpServer3.exe
Press any key to continue . . .

这就是我想要的。现在,当我用“Test2”调用RegQueryValueEx时,我得到:

C:\Test.exe
Press any key to continue . . .
C:\Test.exe

程序崩溃了。任何想法为什么??

非常感谢

1 个答案:

答案 0 :(得分:1)

  1. 您的代码不是安全例外。如果std::string的成员函数抛出std::bad_alloc,您将泄漏一个句柄(HKEY)。
  2. 检查错误返回代码和GetLastError,了解代码失败的更具体原因。
  3. printf("%s\n", FullPath);不应该编译,更不用说了。你确定它不是printf("%s\n", FullPath.c_str());吗?
  4. 您应该使用std::vector而不是固定大小的缓冲区。如果您知道自己总是要获取文件名,则应使用MAX_PATH作为缓冲区大小。
  5. 如果涉及Unicode字符,则此代码将失败。考虑将所有内容切换为wchar_t
  6. char mydata[2000] = {'\0'};< - 为什么{'\0'}而不只是""{}
  7. 您没有使用GetLastError();
  8. 的返回代码执行任何操作
  9. 如果字符串中没有\/,则GetFileNameFromPath将失败,因为std::string::find将返回string.npos
  10. system("PAUSE");应该替换为std::cin.get();