MFC 读写配置文件

Config.h
#ifndef __DLL_CONFIG__
#define __DLL_CONFIG__
#include <string>
using namespace std;

class Config
{
public:
	void OpenConfig(const char* fileName, const char* appName);
	int GetInt(const char* keyName, int* returnValue, int defaultValue);
	char* GetStr(const char* keyName, char* returnValue, int returnSize, const char* defaultValue);
	int SetInt(const char* keyName, int setValue);
	CString SetStr(const char* keyName, CString setValue);
	const char* GetConfigPath();
private:
	string m_appName;
	string m_filePath;
};



#endif //__DLL_CONFIG__


Config.cpp
#include "Config.h"

void Config::OpenConfig(const char* fileName, const char* appName)
{
	char currentDir[150] = { 0 };
	char InitFileName[256] = { 0 };
	GetCurrentDirectoryA(150, currentDir);
	sprintf_s(InitFileName, "%s/%s", currentDir, fileName);
	m_filePath = InitFileName;
	m_appName = appName;
}

int Config::GetInt(const char* keyName, int* returnValue, int defaultValue)
{
	*returnValue = GetPrivateProfileIntA(m_appName.c_str(), keyName, defaultValue, m_filePath.c_str());
	return *returnValue;
}

char* Config::GetStr(const char* keyName, char* returnValue, int returnSize, const char* defaultValue)
{
	GetPrivateProfileStringA(m_appName.c_str(), keyName, defaultValue, returnValue, returnSize, m_filePath.c_str());
	return returnValue;
}

const char* Config::GetConfigPath()
{
	return m_filePath.c_str();
}


int Config::SetInt(const char* keyName, int setValue)
{
	char value[12] = { 0 };
	_itoa(setValue, value, 10);
	WritePrivateProfileStringA(m_appName.c_str(), keyName, value, m_filePath.c_str());
	return setValue;
}

CString Config::SetStr(const char* keyName, CString setValue)
{
	WritePrivateProfileStringW(CString(m_appName.c_str()), CString(keyName), setValue, CString(m_filePath.c_str()));
	return setValue;
}

猜你喜欢

转载自blog.csdn.net/HHCOO/article/details/76208867