[ create a new paste ] login | about

Link: http://codepad.org/jMuWcYdI    [ raw code | fork ]

C++, pasted on Feb 7:
// 
// なんとなく iniファイルRead/Writeなクラス by ミングスレの名無し
// 
// ライセンス:NYSL
//  なんか微妙な気持ちが拭えないが気にしない人向け
// 
// 使い方:
//  IniFileIO ini(hWnd, "vip.ini");
//  ini.beginSection(TEXT("うへへ"));			// [うへへ]
//  ini.setValue(TEXT("鍵1"), TEXT("値1"));	// 鍵1=値1
//  ini.setValue(TEXT("鍵2"), TEXT("値2"));	// 鍵2=値2
//  ini.endSection();
//
// セクション不要なら ***Section() はスルーでおk 

// ----------------------------------------------------------------------- ini_file_io.h
#ifndef _INI_FILE_IO_H_
#define _INI_FILE_IO_H_

#include <windows.h>

#ifdef UNICODE
#include <xstring>
typedef std::wstring std_string;
#else
#include <string>
//typedef std::basic_string<wchar_t> std_string;
typedef std::string std_string;
#endif

class IniFileIO {
	std_string filename;
	std_string current_section;
public:
	IniFileIO(LPCTSTR file);
	IniFileIO(HWND hWnd, LPCTSTR name);
	std_string& getPath();

	void beginSection(LPCTSTR section);
	void endSection();

	std_string getValue(LPCTSTR key);
	std_string getValue(LPCTSTR key, LPCTSTR default_val);
	bool setValue(LPCTSTR key, LPCTSTR value);
};

#endif


// ----------------------------------------------------------------------- ini_file_io.cpp
#include "ini_file_io.h"
#include <stdexcept>

#define MAX_VALUE_SIZE 512
#define DEFAULT_INI_VALUE ""

IniFileIO::IniFileIO(LPCTSTR file)
{
	if(file != NULL) filename = std_string(file);
}

IniFileIO::IniFileIO(HWND hWnd, LPCTSTR name)
{
	TCHAR path[MAX_PATH];
	if(!GetModuleFileName((HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE), path, MAX_PATH)) return;

	std_string tmp(path);
	size_t p = tmp.find_last_of(TEXT('\\'));
	if(p != std_string::npos) 
	{
		tmp = tmp.substr(0, p);
		tmp += TEXT('\\');
		tmp += std_string(name);

		filename = tmp;
	}
}

std_string& IniFileIO::getPath()
{
	return filename;
}

void IniFileIO::beginSection(LPCTSTR section)
{
	current_section = std_string(section);
}

void IniFileIO::endSection()
{
	current_section.erase(0, current_section.size());
}

std_string IniFileIO::getValue(LPCTSTR key)
{
	return getValue(key, TEXT(DEFAULT_INI_VALUE));
}

std_string IniFileIO::getValue(LPCTSTR key, LPCTSTR default_val)
{
	if(filename.empty()) throw std::runtime_error("ini file error");

	TCHAR tmp[MAX_VALUE_SIZE];
	GetPrivateProfileString(current_section.c_str(), key, default_val, tmp, sizeof(tmp)/sizeof(TCHAR), filename.c_str());
	return std_string(tmp);
}

bool IniFileIO::setValue(LPCTSTR key, LPCTSTR value)
{
	if(filename.empty()) throw std::runtime_error("ini file error");

	return WritePrivateProfileString(current_section.c_str(), key, value, filename.c_str()) != NULL;
}


Create a new paste based on this one


Comments: