13d. wxWidgets – wxConfig Usage

OVERVIEW

The purpose of config classes in wxWidgets is to store various information and data which can be retrievable later on. Config data can be stored in a hierarchical manner much like a directory system.

Depending on the underlying platform, configuration data is stored in different ways. For eg.in Linux and Unix, they are stored as files in the disk and in Windows they are stored as keys in the Windows registry. wxWidgets provides an abstract class called wxConfigBase which is then implemented as wxFileConfig and wxRegConfig.

To make things easy, there is a class called wxConfig which automatically works with wxFileConfig and wxRegConfig as required, thus saving you the trouble of dealing with file systems and Windows registry.

In the sample code below, we write some values to wxConfig in a hierarchy. When we load the application with a command line parameter read, it reads the values back from the wxConfig system. Note that the delete config statement is what saves all the values to the wxConfig system. Without that line, nothing would be saved.

SAMPLE CODE

config-usage.cpp
#include  <wx/wxprec.h>
#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/string.h>


int main(int argc, char **argv) {
	wxInitialize();
	wxConfig *config = new wxConfig("myapp");

	if (argc >= 2) {
	  wxString arg = argv[1];
	  if (arg == wxT("read")) {
	    wxPuts(config->Read(wxT("Key 1")));
	    wxPuts(config->Read(wxT("Key 2")));
	    wxPuts(config->Read(wxT("Key 3")));
	    
	    config->SetPath("/folder1");
	    wxPuts(config->Read(wxT("Folder1Key")));

	    config->SetPath("/folder1/folder11");
	    wxPuts(config->Read(wxT("Folder11Key")));
	  }
	  return 1;
	}
	config->Write(wxT("Key 1"), wxT("Value 1"));
	config->Write(wxT("Key 2"), wxT("Value 2"));
	config->Write(wxT("Key 3"), wxT("Value 3"));

	config->SetPath("/folder1/folder11");
	config->Write(wxT("Folder11Key"), wxT("Value in folder 11"));
	config->SetPath("/folder1");
	config->Write(wxT("Folder1Key"), wxT("Value in folder 1"));


	delete config;
	wxPuts(wxT("done"));
	wxUninitialize();
}

The output is given below

Be the first to comment

Leave a Reply

Your email address will not be published.


*