連想配列ファイル読み込みクラス

全然なんてことはないですが、あると便利なクラス。

1.area

# マップの左上座標
map_lt_x=-50
map_lt_y=0
map_lt_z=-50

# マップの右上座標
map_rb_x=50
map_rb_y=0
map_rb_z=50

# 木の座標
tree_x=5
tree_y=0
tree_z=-10

# プレイヤーの初期座標
player_x=0
player_y=0
player_z=0

こんな「キー」と「値」からなるシンプルなファイルを読み込むクラスです。
 
PropertyLoader.h

#pragma once

#include <string>
#include <map>

using namespace std;

/**
 * プロパティファイル読み込みクラス
 */
class CPropertyLoader
{
public:
	typedef map<string, string> ProperyMap;
private:
	ProperyMap m_map;
public:
	CPropertyLoader(void){};
	~CPropertyLoader(void){};

	void Load(string filepath);
	string Find(string key)
	{
		if(m_map.count(key) == 0) return string("");
		else         return m_map.find(key)->second;
	}
	ProperyMap GetAll() {return m_map;}
};

 
PropertyLoader.cpp

#include ".\propertyloader.h"
#include <fstream>

#define __DEBUG_PROPERTYLOADER // デバッグを無効にする場合はコメントアウト

// ============================================================================
// プロパティファイル読み込み
// @param  filepath ファイルパス
// @throw ファイルが存在しないとき
// ============================================================================
void CPropertyLoader::Load(string filepath)
{
	ifstream ifs(filepath.c_str());
	if(ifs.fail())
	{
		throw "Can't open file";
	}
	m_map.clear();

	char tmp[256];

	ifs.getline(tmp, 256);
	while(!ifs.eof())
	{
		string line(tmp);
		// コメント行
		if(line.substr(0, 1).compare("#") != 0)
		{
			// 無効行
			size_t nEq = line.find("=");
			if(nEq != -1)
			{
				string key = line.substr(0, nEq);
				string val = line.substr(nEq+1);
				m_map.insert(pair<string, string>(key, val));
			}
		}
		ifs.getline(tmp, 256);
	}
	
	ifs.close();
}

#ifdef __DEBUG_PROPERTYLOADER
#include <iostream>
// ============================================================================
// テストドライバ
// ============================================================================
void main()
{
	CPropertyLoader pl;
	try
	{
		pl.Load("1.area");
		CPropertyLoader::ProperyMap map = pl.GetAll();
		CPropertyLoader::ProperyMap::iterator iter = map.begin();
		int i = 0;
		while(iter != map.end())
		{
			cout << i << ":" << endl;
			cout << "  key -> " << iter->first << endl;
			cout << "  val -> " << iter->second << endl;
			++iter;
			i++;
		}
	}
	catch(...)
	{
		cout << "ファイル読み込みエラー" << endl;
	}
}

#endif

 
実行結果はこんな感じです。

0:
  key -> map_lt_x
  val -> -50
1:
  key -> map_lt_y
  val -> 0
2:
  key -> map_lt_z
  val -> -50
3:
  key -> map_rb_x
  val -> 50
4:
  key -> map_rb_y
  val -> 0
5:
  key -> map_rb_z
  val -> 50
6:
  key -> player_x
  val -> 0
7:
  key -> player_y
  val -> 0
8:
  key -> player_z
  val -> 0
9:
  key -> tree_x
  val -> 5
10:
  key -> tree_y
  val -> 0
11:
  key -> tree_z
  val -> -10