使用wxwidgets操作 .ini文件

1. 什么是.ini文件:

        在程序中经常要用到设置或者把其他少量数据存盘,以便在下一次执行的时候可以使用,比如保存本次程序执行时窗口的位置,大小,一些用户数据等。

在Dos下编程的时候,我们一般自己产生一个文件,自己把这些数据存入文件,下一次执行的时候再读取出来。当然应用程序里也可以这么做,但是Windows

已经给我们提供了两种方便的方法,就是使用注册表或者ini文件(Profile )来保存少量的数据,这里整理下基于wxwidgets框架对ini的操作。

 
#include "wx/wx.h"
#include "wx/stdpaths.h"
#include "wx/filename.h"
#include "wx/file.h"
#include "wx/fileconf.h" //file config.ini 
#include "wx/wfstream.h"

class MyApp:public wxApp
{
      virtual bool OnInit();
      wxString GetWorkPath();
      void LoadConfig();
      void SaveConfig();
}

bool MyApp::OnInit()
{
      wxFileInputStream is(this->GetWorkPath()+"config.ini");
      wxFileConfig* config = new wxFileConfig(is);
      wxConfigBase::Set(config);

      this->SaveConfig();
      ...
      return true;

}
wxString MyApp::GetWorkPath()
{
	wxString apppath;
	wxStandardPathsBase& stpd = wxStandardPaths::Get();

	wxFileName exeFile(stpd.GetExecutablePath());
	apppath = exeFile.GetPath(wxPATH_GET_VOLUME|wxPATH_GET_SEPARATOR); 

	return apppath;
}

void MyApp::LoadConfig()
{
	wxFileConfig* config = (wxFileConfig*)wxConfigBase::Get();

	double factor1 = 0.0;
	double factor2 = 0.0;
	//wxConfigBase::Read(wxString& key, double* d, double default)
	// read a double value,return true if the value was found,else default is used instead
	config->Read(wxT("TST/Factor/factor1"), &factor1, 2.5);
	config->Read(wxT("TST/Factor/factor2"), &factor2, 5.0);
	//m_panel1->GetValue().SetValue(factor1, factor2);

	double offset1 = 0.0;
	double offset2 = 0.0;
	config->Read(wxT("TST/Offset/offset1"), &offset1, 2.5);
	config->Read(wxT("TST/Offset/offset2"), &offset2, 5.0);
	//m_panel2.GetValue().SetValue(offset1, offset2);
}
void MyApp::SaveConfig()
{
	wxFileConfig* config = (wxFileConfig*)wxConfigBase::Get();
	double factor1 = 7.5, offset1 = 10.0;
	double factor2 = 7.5, offset2 = 10.0;

	config->Write(wxT("TST/Factor/factor1"), factor1);
	config->Write(wxT("TST/Factor/factor2"), factor2);
	config->Write(wxT("TST/Offset/offset1"), offset1);
	config->Write(wxT("TST/Offset/offset2"), offset2);

	wxString path = this->GetWorkPath()+wxT("config.ini");
	wxFileOutputStream os(path);
	if(os.IsOk())
		config->Save(os);
}

 

最终保存在config.ini文件中如下:

[TST]
[TST/Factor]
factor1=7.5
factor2=7.5
[TST/Offset]
offset1=10
offset2=10

 

注意。GetWorkPath()获取到当前生成的.exe文件所在的目录,config.ini文件应该在相应的目录下,不然会报一个断点。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值