WIN32 封装INI文件类
时间: 2023-12-06 12:02:10 浏览: 34
以下是使用WIN32 API封装INI文件类的示例代码:
```cpp
#include <Windows.h>
#include <string>
class IniFile {
public:
IniFile(const std::wstring& filename) : m_filename(filename) {}
std::wstring GetValue(const std::wstring& section, const std::wstring& key) const {
wchar_t buffer[256];
GetPrivateProfileStringW(section.c_str(), key.c_str(), L"", buffer, sizeof(buffer), m_filename.c_str());
return std::wstring(buffer);
}
void SetValue(const std::wstring& section, const std::wstring& key, const std::wstring& value) {
WritePrivateProfileStringW(section.c_str(), key.c_str(), value.c_str(), m_filename.c_str());
}
private:
std::wstring m_filename;
};
// 示例用法
int main() {
IniFile ini(L"config.ini");
std::wstring value = ini.GetValue(L"SectionName", L"KeyName");
if (!value.empty()) {
wprintf(L"Value: %s\n", value.c_str());
} else {
wprintf(L"Value not found.\n");
}
ini.SetValue(L"SectionName", L"KeyName", L"NewValue");
return 0;
}
```
在上述示例中,我们定义了一个`IniFile`类,该类封装了读取和写入INI文件的功能。它使用`GetPrivateProfileStringW`函数来读取INI文件中的值,并使用`WritePrivateProfileStringW`函数来写入INI文件。
在`IniFile`类中,我们提供了`GetValue`和`SetValue`两个成员函数,用于读取和写入INI文件中的值。这些函数接受`section`和`key`作为参数,并返回对应的值。
在示例的`main`函数中,我们创建了一个`IniFile`对象,传入INI文件的路径。然后,我们使用`GetValue`函数读取名为"SectionName"的section中的"KeyName"的值,并打印到控制台。接着,我们使用`SetValue`函数将"NewValue"写入到"SectionName"的"KeyName"中。
你可以根据实际需求修改和扩展这个示例。希望这个示例能够帮助你封装一个简单的INI文件类。如果有任何进一步的问题,请随时提问。