MFC 读取配置文件(封装)

来源:互联网 发布:java项目实战视频 编辑:程序博客网 时间:2024/06/05 09:25

目前只封装了string类型的读和写配置文件

利用了 Windows API 现有的函数,很简单:

WritePrivateProfileStringW(    _In_opt_ LPCWSTR lpAppName,    _In_opt_ LPCWSTR lpKeyName,    _In_opt_ LPCWSTR lpString,    _In_opt_ LPCWSTR lpFileName    );GetPrivateProfileStringW(    _In_opt_ LPCWSTR lpAppName,    _In_opt_ LPCWSTR lpKeyName,    _In_opt_ LPCWSTR lpDefault,    _Out_writes_to_opt_(nSize, return + 1) LPWSTR lpReturnedString,    _In_     DWORD nSize,    _In_opt_ LPCWSTR lpFileName    );

这一段是配置文件的路径,可以写在APP开始启动的地方,路径szCfgPath是全局变量,可以声明在专门的全局变量的一个类里面,在用extern 配置文件的地址

szCfgPath = L"";::GetCurrentDirectory(260, szCfgPath.GetBuffer(260));szCfgPath.ReleaseBuffer();szCfgPath += "\\config.ini";if (!PathFileExists(szCfgPath))//不存在则创建{    CFile file;    if (!file.Open(szCfgPath, CFile::modeCreate | CFile::modeReadWrite))    {        MessageBox(NULL, L"创建配置文件失败", L"警告", MB_OK);        return false;    }}

配置文件的封装(只有char* 类型的读写)

//////////////////////////////////////////读写配置文件/////////////////////////////////////////////bool sh_cfg_set_string_value(char* Key, LPCWSTR Value){    USES_CONVERSION;    ::WritePrivateProfileString(L"SignIn", A2W(Key), Value, szCfgPath);    return true;}char* sh_cfg_get_string_value(char* Key, char* DefaultValue){    USES_CONVERSION;    CString value;    ::GetPrivateProfileString(L"SignIn", A2W(Key), A2W(DefaultValue), value.GetBuffer(32), 32, szCfgPath);    value.ReleaseBuffer();    return T2A(value);}

示例:(预先在SysCfg的类里声明)

// 配置文件的Key#define LB_CFG_KEY_MASTER_IP                "MasterIP"// 配置文件的默认值#define LB_CFG_DEFAULT_MASTER_IP            ""// 主机IP地址void CSysCfg::SetMasterIP(LPCWSTR Value){    sh_cfg_set_string_value(LB_CFG_KEY_MASTER_IP, Value);}char* CSysCfg::GetMasterIP(){    return sh_cfg_get_string_value(LB_CFG_KEY_MASTER_IP, LB_CFG_DEFAULT_MASTER_IP);}

使用时直接就可以使用(g_pSysCfg是CSysCfg类的指针)

g_pSysCfg->GetMasterIP();g_pSysCfg->SetMasterIP(A2W(szIP));
0 0