Here is my code:
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <tchar.h>
#define MAX_KEY_LENGTH 6
void CheckForUIMatch(TCHAR *ui, TCHAR *UIToFind, TCHAR *UIFound);
int _tmain(int argc, LPTSTR argv[])
{
TCHAR UIToFind[24] = _T("hi***;en-US; ");
TCHAR UIFound[24] = _T("");
LPCTSTR placeToLook = _T("SYSTEM\\CurrentControlSet\\Control\\MUI\\UILanguages");
HKEY UIKey;
DWORD subkeyCounter = 0;
TCHAR subkeyName[MAX_KEY_LENGTH];
DWORD subkeyLength;
DWORD subkeyAmount = 0;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, placeToLook , 0, KEY_READ, &UIKey) == ERROR_SUCCESS) {
RegQueryInfoKey(UIKey, NULL, NULL, NULL, &subkeyAmount, NULL, NULL, NULL, NULL, NULL, NULL, NULL); // Get the length of the longest subkey.
for (subkeyCounter = 0; subkeyCounter < subkeyAmount; subkeyCounter++) {
subkeyLength = MAX_KEY_LENGTH;
RegEnumKeyEx(UIKey,
subkeyCounter,
subkeyName,
&subkeyLength,
NULL,
NULL,
NULL,
NULL);
CheckForUIMatch(subkeyName, UIToFind, UIFound);
}
} else {
_tprintf(L"Faild to open the registry key!");
}
_tprintf(_T("Match: %s"), UIFound);
return 0;
}
void CheckForUIMatch(TCHAR *ui, TCHAR *UIToFind, TCHAR *UIFound)
{
int charToMatch;
TCHAR* token = _tcstok(UIToFind, L";");
while(token != NULL) {
/* Check for exact match or general match */
if ((token[_tcslen(token)-2] == '*') && (token[_tcslen(token)-1] == '*')) { // make general lang match
charToMatch = 2;
} else {
charToMatch = 5; // make exact lang match
}
_tprintf(L"\ntoken: %s, to match %d.\n", token, charToMatch); //Debug
if(!_tcsncmp(token, ui, charToMatch)) {
_tcsncat(UIFound, ui, charToMatch);
_tcscat(UIFound, _T(";"));
}
token = _tcstok(NULL, L";");
}
}
The problem:
It seems that the while loop at the CheckForUIMatch is doing its work only once, but at the second time the loop is run (e.g. when there is more than one UI that is found in the registry), it loop only on one of the tokens (e.g. hi***) and not at the second, once it end the loop and needs to get the second token i can see in the debugger that it get BatPointer instead of the second token.
If i put the UIToFind TCHAR directly inside the CheckForUIMatch function, everything is working fine, i am don’t know why? is anybody knows ?
strtokmodifies the search string in-place to delimit the substrings. Your search string evolves thus as you callstrtok:When you try to reuse this string in a second round of calls to
strtok, the function sees"hi***"because the first'\0'terminates the string.Instead of splitting the string each time, split it once or declare it as an array, e.g.: