xref: /MusicPlayer2/MusicPlayer2/IniHelper.h (revision 4b9b29893b3bb42cad0f3ee69501a6a01e2c802f)
1 //ini读写类
2 //使用时将ini文件路径通过构造函数参数传递
3 //在向ini文件写入数据时,需要在最后调用Save()函数以将更改保存到文件
4 //默认以UTF8_BOM编码保存,如果要以ANSI保存,请调用SetSaveAsUTF8(false);
5 #pragma once
6 #include "Common.h"
7 
8 class CIniHelper
9 {
10 public:
11 	CIniHelper(const wstring& file_path);
12     // 从资源文件加载ini (只能读取)
13     CIniHelper(UINT id, CodeType code_type = CodeType::UTF8);
14 	~CIniHelper();
15 
16 	void SetSaveAsUTF8(bool utf8);
17 
18 	void WriteString(const wchar_t* AppName, const wchar_t* KeyName, const wstring& str);
19 	wstring GetString(const wchar_t* AppName, const wchar_t* KeyName, const wchar_t* default_str) const;
20 	void WriteInt(const wchar_t * AppName, const wchar_t * KeyName, int value);
21 	int GetInt(const wchar_t * AppName, const wchar_t * KeyName, int default_value) const;
22     void WriteDouble(const wchar_t * AppName, const wchar_t * KeyName, double value);
23     double GetDouble(const wchar_t * AppName, const wchar_t * KeyName, double default_value) const;
24 	void WriteBool(const wchar_t * AppName, const wchar_t * KeyName, bool value);
25 	bool GetBool(const wchar_t * AppName, const wchar_t * KeyName, bool default_value) const;
26 	void WriteIntArray(const wchar_t * AppName, const wchar_t * KeyName, const int* values, int size);		//写入一个int数组,元素个数为size
27 	void GetIntArray(const wchar_t * AppName, const wchar_t * KeyName, int* values, int size, int default_value = 0) const;		//读取一个int数组,储存到values,元素个数为size
28 	void WriteBoolArray(const wchar_t * AppName, const wchar_t * KeyName, const bool* values, int size);
29 	void GetBoolArray(const wchar_t * AppName, const wchar_t * KeyName, bool* values, int size, bool default_value = false) const;
30     void WriteStringList(const wchar_t * AppName, const wchar_t * KeyName, const vector<wstring>& values);      //写入一个字符串列表,由于保存到ini文件中时字符串前后会加上引号,所以字符串中不能包含引号
31     void GetStringList(const wchar_t * AppName, const wchar_t * KeyName, vector<wstring>& values, const vector<wstring>& default_value) const;
32 
33 	CVariant GetValue(const wchar_t * AppName, const wchar_t * KeyName, CVariant default_values) const;
34 	void WriteValue(const wchar_t * AppName, const wchar_t * KeyName, CVariant value);
35 
36     // 获取带有指定前缀的所有AppName(不含前缀)
37     vector<wstring> GetAllAppName(const wstring& prefix) const;
38     // 获取一个AppName下所有键值对
39     void GetAllKeyValues(const wstring& AppName, std::map<wstring, wstring>& map) const;
40 
41 	bool Save();		//将ini文件保存到文件,成功返回true
42 
43 protected:
44 	wstring m_file_path;
45 	wstring m_ini_str;
46 	bool m_save_as_utf8{ true };		//是否以UTF8编码保存
47 
48     static void UnEscapeString(wstring& str);
49 	void _WriteString(const wchar_t* AppName, const wchar_t* KeyName, const wstring& str);
50 	wstring _GetString(const wchar_t* AppName, const wchar_t* KeyName, const wchar_t* default_str) const;
51 };
52 
53