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文件应该在相应的目录下,不然会报一个断点。