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
程序崩溃了。任何想法为什么??
非常感谢
答案 0 :(得分:1)
std::string
的成员函数抛出std::bad_alloc
,您将泄漏一个句柄(HKEY
)。GetLastError
,了解代码失败的更具体原因。printf("%s\n", FullPath);
不应该编译,更不用说了。你确定它不是printf("%s\n", FullPath.c_str());
吗?std::vector
而不是固定大小的缓冲区。如果您知道自己总是要获取文件名,则应使用MAX_PATH
作为缓冲区大小。wchar_t
。char mydata[2000] = {'\0'};
< - 为什么{'\0'}
而不只是""
或{}
?GetLastError();
\
或/
,则GetFileNameFromPath
将失败,因为std::string::find
将返回string.npos
。system("PAUSE");
应该替换为std::cin.get();
。