Simple library of INI file parser.

Dependents:   TrainInfoSample WatchSensorMail

IniFile.h

Committer:
rinosh2
Date:
2010-11-17
Revision:
1:3601c7feb547
Parent:
0:995403221573

File content as of revision 1:3601c7feb547:

///////////////////////////////////////////////////////////////////////////////
// IniFile: .ini file parser   by rinos 2010
///////////////////////////////////////////////////////////////////////////////

// Ini file value (int/bool/string)
// Key1 = 123            -> 123         (int)
// Key2 = 0x123          -> 291         (int)
// Key3 = FALSE          -> false       (bool)
// Key4 = TRUE           -> true        (bool)
// Key5 = 123            -> true        (bool)
// key6 =   abc "def     -> 'abc "def'  (string)
// key7 = " ghi "jkl "   -> ' ghi "jkl '(string)
// #comment line

#ifndef __INI_FILE_H__
#define __INI_FILE_H__

#include "mbed.h"

class IniFile{
	// defines /////////////////////////////////////////////////////////////////
public:
	// data type
	typedef enum {
		DTYPE_INT	= -1,
		DTYPE_BOOL	= -2,
		// other string
	} DataType;

	// For the multiple read
	struct IniList{
		const char* key;	// key name  (set NULL for list end)
		int   typelen;		// >0: buffer length, <0: DataType
		void* buf;			// return buffer
	};

	// error code
	typedef enum {
		S_SUCCESS,
		S_OPEN_ERROR,
		S_NOT_OPENED,
		S_NO_KEY,
		S_BUFFER_TOO_SHORT,
		S_FORMAT_ERROR,
	} Status;
	
	// internal member/method //////////////////////////////////////////////////
private:
	FILE* m_fp;

	// Invalid method
protected:
	IniFile(const IniFile& v);
	const IniFile& operator =(const IniFile& v);

public:
	IniFile(const char* file = 0);
	~IniFile();

	// Access methods
	Status open(const char* file);
	Status close();
	
	Status get(const char* key, char* ret, int ret_size);
	Status get(const char* key, int&  ret);
	Status get(const char* key, bool& ret);
	Status get(const IniList* inilist);
	
	// For easy acccess
	static Status getval(const char* inifile, const char* key, char* ret, int ret_size){
		return IniFile(inifile).get(key, ret, ret_size);
	}
	static Status getval(const char* inifile, const char* key, int& ret){
		return IniFile(inifile).get(key, ret);
	}
	static Status getval(const char* inifile, const char* key, bool& ret){
		return IniFile(inifile).get(key, ret);
	}
	static Status getval(const char* inifile, const IniList* inilist){
		return IniFile(inifile).get(inilist);
	}

	// for string triming
	static Status strtrim(char* dst, const char* src, int dst_size); // move to public
};

// for the table
#define INIFILE_INT(key,  val)		{key,	IniFile::DTYPE_INT,		&val}
#define INIFILE_BOOL(key, val)		{key,	IniFile::DTYPE_BOOL,	&val}
#define INIFILE_STR(key, buf, size)	{key,	size,					buf}
#define INIFILE_END					0

#endif