Reputation: 141
Regedit Screenshot http://i54.tinypic.com/3503vi8.jpg
Now, this code:
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");
The function GetFilenameFromPath is defined as:
std::string GetFileNameFromPath (std::string str) {
size_t found;
found=str.find_last_of("/\\");
return str.substr(found+1);}
When I call RegQueryValueEx with "QKSMTPServer3" as the second parameter, here is the output:
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 . . .
Which is what I want. Now, when I call RegQueryValueEx with "Test2", I get:
C:\Test.exe
Press any key to continue . . .
C:\Test.exe
and the program crashes. Any ideas why??
Thank you very much
Upvotes: 1
Views: 255
Reputation: 106530
std::string
's member functions throw std::bad_alloc
, you will leak a handle (the HKEY
).GetLastError
for a more specific reason why your code is failing.printf("%s\n", FullPath);
should not compile, much less run. Are you sure it's not printf("%s\n", FullPath.c_str());
?std::vector
. If you know that you're always going to be getting a file name, you should use MAX_PATH
as your buffer size.wchar_t
instead.char mydata[2000] = {'\0'};
<-- Why {'\0'}
instead of just ""
or {}
?GetLastError();
\
or /
in the string, GetFileNameFromPath
will fail because std::string::find
will return string.npos
.system("PAUSE");
should really be replaced with std::cin.get();
instead.Upvotes: 1