头文件:
#ifndef INIFILE_H
#define INIFILE_H
#include "string"
#include <iostream>
using namespace std;
class IniFile
{
public:
IniFile(string m_szFileName);
void writeInteger(string szSection, string szKey, int iValue);
void writeString(string szSection, string szKey, string szValue);
int readInteger(string szSection, string szKey, int iDefaultValue);
string readString(string szSection, string szKey, string szDefaultValue);
void removeSection(string szSection);
void removeKey(string szSection, string szKey);
private:
string m_szFileName;
};
#endif //INIFILE_H
CPP:
#include "ini_file.h"
#include <Windows.h>
#include "DbgPrint.h"
using namespace std;
#define MAX_LEN 255
IniFile::IniFile(string szFileName)
{
//C盘无权限创建文件
std::string szAppdata = getenv("appdata");
m_szFileName = szAppdata+"\\zz\\"+szFileName;
}
void IniFile::writeInteger(string szSection, string szKey, int iValue)
{
char szValue[MAX_LEN] = {0};
_ltoa_s(iValue,szValue,10);
if (!WritePrivateProfileStringA(szSection.c_str(), szKey.c_str(),
szValue, m_szFileName.c_str()))
{
DbgPrint("[IniFile]writeInteger failed,err = %d",GetLastError());
}
}
void IniFile::writeString(string szSection, string szKey, string szValue)
{
if (!WritePrivateProfileStringA(szSection.c_str(), szKey.c_str(),
szValue.c_str(), m_szFileName.c_str()))
{
DbgPrint("[IniFile]writeString failed,err = %d",GetLastError());
}
DbgPrint("[IniFile]writeString ok,err = %d",GetLastError());
}
int IniFile::readInteger(string szSection, string szKey, int iDefaultValue)
{
int iResult = GetPrivateProfileIntA(szSection.c_str(), szKey.c_str(),
iDefaultValue, m_szFileName.c_str());
return iResult;
}
string IniFile::readString(string szSection, string szKey, string szDefaultValue)
{
char szResult[MAX_LEN];
memset(szResult, 0x00, MAX_LEN);
GetPrivateProfileStringA(szSection.c_str(), szKey.c_str(),
szDefaultValue.c_str(), szResult, MAX_LEN, m_szFileName.c_str());
return szResult;
}
void IniFile::removeSection(string szSection)
{
if (!WritePrivateProfileStringA(szSection.c_str(),NULL,NULL,m_szFileName.c_str()))
{
DbgPrint("[IniFile]removeSection failed,err = %d",GetLastError());
}
}
void IniFile::removeKey(string szSection, string szKey)
{
if (!WritePrivateProfileStringA(szSection.c_str(),szKey.c_str(),NULL,m_szFileName.c_str()))
{
DbgPrint("[IniFile]removeKey failed,err = %d",GetLastError());
}
}