RegQueryValueEx与REG_MULTI_SZ,如何读取注册表中REG_MULTI_SZ类型的数据?
今天同事在使用 RegQueryValueEx 查询注册表键值时发现总是无法获取该项的内容,返回错误代码为234,FormatMessage后显示"no more data error"。代码如下:
ULONG type = REG_MULTI_SZ;
UCHAR buffer[256] = {0};
ULONG length;
ULONG ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, buffer, &length);
UCHAR buffer[256] = {0};
ULONG length;
ULONG ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, buffer, &length);
开始怀疑RegQueryValueEx的缓冲区设置的不够大,将256修改为512后仍然是同样的错误。
查询了一下MSDN说要根据length返回的长度来为缓冲区分配内存,将代码修改如下:
1 ULONG type = REG_MULTI_SZ;
2 PUCHAR buffer = NULL;
3 ULONG length;
4 ULONG ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, NULL, &length);
5
6 buffer = new UCHAR[length];
7 memset(buffer, 0, length);
8
9 ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, buffer, &length);
10 if (ret != ERROR_SUCCESS)
11 {
12 cout << "RegQueryValueEx error " << GetLastError() << endl;
13 }
2 PUCHAR buffer = NULL;
3 ULONG length;
4 ULONG ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, NULL, &length);
5
6 buffer = new UCHAR[length];
7 memset(buffer, 0, length);
8
9 ret = RegQueryValueEx(hKey, "HardwareID", 0, &type, buffer, &length);
10 if (ret != ERROR_SUCCESS)
11 {
12 cout << "RegQueryValueEx error " << GetLastError() << endl;
13 }
运行一切OK啦。