windows下的配置文件读取和写入类
头文件
#pragma once
#include <windows.h>
#include <string>
#include <stdio.h>
#include <iostream>
#include <numeric>
#include <sstream>
#include <ostream>
using namespace std;
#define MAX_FILE_NAME_LEN 256
class CConfig
{
public:
CConfig(void);
~CConfig(void);
private:
//用来保存配置文件名
char cfg_IniName[100];
string do_fraction(long double value, int decplaces);
public:
int GetConfigInt(string AppName, string KeyName, int nDefault);
string GetConfigstring(string AppName, string KeyName, string strDefault);
BOOL SetConfigInt(string AppName, string KeyName, int IntWrite);
BOOL SetConfigFloat(string AppName, string KeyName, double FloatWrite, int decplaces);
BOOL SetConfigStr(string AppName, string KeyName, string WriteStr);
float GetConfigFloat(string AppName, string KeyName);
};
源文件
#include "StdAfx.h"
#include "Config.h"
CConfig::CConfig(void)
{
memset(cfg_IniName,0,sizeof(cfg_IniName));
GetCurrentDirectory ( MAX_FILE_NAME_LEN-32,cfg_IniName );
char cfg_IniShortName[]="\\Config.INI";
strcat ( (char*)cfg_IniName, (char*)cfg_IniShortName );
}
CConfig::~CConfig(void)
{
}
int CConfig::GetConfigInt(string AppName, string KeyName, int nDefault)
{
return GetPrivateProfileInt ( AppName.c_str(), KeyName.c_str(),nDefault, cfg_IniName);
}
string CConfig::GetConfigstring(string AppName, string KeyName, string strDefault)
{
char Configstr[1000];
memset(Configstr,0,sizeof(Configstr));
GetPrivateProfileString(AppName.c_str(),KeyName.c_str(),"",Configstr ,sizeof(Configstr),cfg_IniName);
string configstr(Configstr);
if (configstr.empty())
{
return strDefault;
}
else
{
return configstr;
}
}
BOOL CConfig::SetConfigInt(string AppName, string KeyName, int IntWrite)
{
string writeStr=do_fraction(IntWrite,0);
return WritePrivateProfileString(AppName.c_str(),KeyName.c_str(),writeStr.c_str(),cfg_IniName);
}
string CConfig::do_fraction(long double value, int decplaces)
{
int prec=numeric_limits<double>::digits10; // 18
ostringstream out;
out.precision(prec);//覆盖默认精度
out<<value;
string str= out.str(); //从流中取出字符串 数值现在存储在str中,等待格式化。
char DECIMAL_POINT='.'; //
size_t n=str.find(DECIMAL_POINT);
size_t eposion=str.find('e');
if (eposion==string::npos)
{
if((n!=string::npos)&&n+decplaces<str.size())
{
str[n+decplaces]='\0';
}
str.swap(string(str.c_str()));
}
return str;
}
BOOL CConfig::SetConfigFloat(string AppName, string KeyName, double FloatWrite, int decplaces=3)
{
string writeStr=do_fraction(FloatWrite,decplaces);
return WritePrivateProfileString(AppName.c_str(),KeyName.c_str(),writeStr.c_str(),cfg_IniName);
}
BOOL CConfig::SetConfigStr(string AppName, string KeyName, string WriteStr)
{
return WritePrivateProfileString(AppName.c_str(),KeyName.c_str(),WriteStr.c_str(),cfg_IniName);
}
float CConfig::GetConfigFloat(string AppName, string KeyName)
{
string FloatStr=GetConfigstring(AppName,KeyName,"");
if (FloatStr.empty())
{
return 0.0000;
}
else
{
return atof(FloatStr.c_str());
}
return 0;
}