c++ - 在 C++ 中递归搜索注册表
问题描述
我的搜索注册表功能有问题。我的目标是输入键名并遍历注册表树,直到找到具有此名称的键。我的函数可以遍历整个树(深度优先),但问题在于搜索 - 我只能成功搜索“第一级”上的键。但是,如果我尝试搜索,例如,HKEY_CURRENT_USER\AppEvents\Schemes,“Schemes”键将被跳过。对于搜索,我使用 found 标志,想法是在设置为 false 时继续搜索。但是 if (!found) { //function code } 和 while (!found) 似乎都对我没有用。我错过了什么以及如何解决它?
我的代码是:
#define BUFF_SIZE 400
void searchKeys(HKEY, string, TCHAR*, bool);
int main()
{
HKEY rootKey= HKEY_CLASSES_ROOT;
int keyMenu;
TCHAR searchedName[BUFF_SIZE];
bool found = false;
cout << "Select root key: " << endl;
cout << "1 - HKEY_CLASSES_ROOT\n2 - HKEY_CURRENT_USER\n3 - HKEY_LOCAL_MACHINE\n4 - HKEY_USERS\n5 - HKEY_CURRENT_CONFIG"<<endl;
cin >> keyMenu;
switch (keyMenu) {
case 1: rootKey = HKEY_CLASSES_ROOT;
break;
case 2: rootKey = HKEY_CURRENT_USER;
break;
case 3: rootKey = HKEY_LOCAL_MACHINE;
break;
case 4: rootKey = HKEY_USERS;
break;
case 5: rootKey = HKEY_CURRENT_CONFIG;
break;
default:
cout << "This root key does not exist" << endl;
system("PAUSE");
return 0;
}
cout << "Enter key name to search: " << endl;
cin >> searchedName;
cout << "\n";
string subKeyPath = "";
searchKeys(rootKey, subKeyPath, searchedName, found);
system("PAUSE");
return 0;
}
void searchKeys(HKEY rootKey, string subKeyPath, TCHAR* searchedName, bool found) {
HKEY subKey;
DWORD subKeyCount, buffSize;
char subKeyBuff[BUFF_SIZE];
char result[BUFF_SIZE];
TCHAR sbNameBuf[BUFF_SIZE];
const char * subKeyName;
subKeyName = subKeyPath.c_str();
copy(subKeyPath.begin(), subKeyPath.end(), sbNameBuf);
//if (!found) {
//while (!found) {
DWORD output = RegOpenKeyEx(rootKey, subKeyName, NULL, KEY_ALL_ACCESS, &subKey); //open specified root catalogue
if (output != ERROR_SUCCESS) return;
RegQueryInfoKey(subKey, NULL, NULL, NULL, &subKeyCount, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //get info about root key
if (!subKeyCount) return;
for (DWORD i = 0; i < subKeyCount && !found; i++) {
buffSize = sizeof(subKeyBuff);
RegEnumKeyEx(subKey, i, subKeyBuff, &buffSize, NULL, NULL, NULL, NULL);
string keyName = subKeyBuff;
if (strcmp(subKeyBuff, searchedName) == 0) {
found = true;
}
else {
cout << subKeyBuff << endl;
}
keyName = subKeyPath + subKeyBuff + "\\";
RegOpenKeyEx(rootKey, subKeyName, NULL, KEY_ALL_ACCESS, &subKey);
RegQueryInfoKey(subKey, NULL, NULL, NULL, &subKeyCount, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //get subKeyCount
if (subKeyCount) {
searchKeys(rootKey, keyName, searchedName, found);
}
}
//}
//}
}
解决方案
这个问题的解决方案是简单地使 bool found 变量成为全局变量。此外,engf-010 评论对于查看所有键很有用。
推荐阅读
- powershell - 命令行什么都不显示没有输出
- java - java - 如何修改xml文档并在java中将其作为字符串返回?
- grafana - Grafana 不更新仪表板面板
- java - 无法使用 Eclipse 运行 Jhipster 应用程序。java.lang.LayerInstantiationException:
- windows - DSC用来配置GPO?
- python - 为博客制作网页点击计数/趋势部分
- javascript - Jasmine 测试方法是否仅在内部方法是 Function 的实例时才调用另一个方法
- java - 如何摆脱 aspose.words 中的空白页?
- python - 如何使用 HTML 表单输入类型文件和烧瓶将图像保存到静态文件夹内的文件夹中
- sql - 我如何计算 PostgreSQL 中两个时间戳之间的差异?