使用单例模式实现配置文件读写,且具有线程安全性。
#include<iostream>
#include <windows.h>
#include<fstream>
using namespace std;
//Ty 使用单例模式实现配置文件的读写,具有线程安全的特性
//2021.03.17
CRITICAL_SECTION cs;
class CIniFileTool
{
private:
CIniFileTool()
{
InitializeCriticalSection(&cs);
}
~CIniFileTool()
{
DeleteCriticalSection(&cs);
}
//检测文件是否存在
bool bExistIniFile(const char *pStrFilename)
{
std::fstream _file;
_file.open(pStrFilename, ios::in);
bool ret = false;
if (_file)
{
ret = true;
}
_file.close();
return ret;
}
public:
//获取唯一实例
static CIniFileTool &GetIniFileTool()
{
static CIniFileTool m_tool;
return m_tool;
}
//向配置文件写数据
bool WriteIniFile(const char *m_pIniFileName,const char *m_rootkey,const char *strKey,const char *strValue_In)
{
if (!m_pIniFileName || !strKey || !m_rootkey || !strValue_In)
{
return false;
}
if (!bExistIniFile(m_pIniFileName))
{
return false;
}
try
{
EnterCriticalSection(&cs);
bool ret = WritePrivateProfileString(m_rootkey, strKey, strValue_In, m_pIniFileName);
LeaveCriticalSection(&cs);
return ret;
}
catch (...)
{
LeaveCriticalSection(&cs);
return false;
}
return true;
}
//从配置文件读数据
bool ReadIniFile(const char *m_pIniFileName, const char *m_rootkey, const char *strKey, char * strValue_Out,int noutsize)
{
if (!m_pIniFileName || !strKey || !strKey || !strValue_Out)
{
return false;
}
if (!bExistIniFile(m_pIniFileName))
{
return false;
}
try
{
EnterCriticalSection(&cs);
int n = GetPrivateProfileString(m_rootkey, strKey,"error", strValue_Out, noutsize, m_pIniFileName);
LeaveCriticalSection(&cs);
if (n < 0)
{
return false;
}
}
catch (...)
{
LeaveCriticalSection(&cs);
return false;
}
return true;
}
};
void play()
{
CIniFileTool &s = CIniFileTool::GetIniFileTool();
char buf[24] = { 0 };
bool ret = s.ReadIniFile("C:\\Users\\t04601\\Desktop\\1.ini", "test", "la", buf, 24);
if (ret)
{
cout << buf << endl;
}
else
{
cout << "配置文件读取失败!\n";
}
ret = s.WriteIniFile("C:\\Users\\t04601\\Desktop\\1.ini", "test", "la", "My name is Ty");
if (ret)
{
cout << "配置文件写入成功!\n";
}
else
{
cout << "配置文件写入失败!\n";
}
}
void main()
{
play();
system("pause");
}
结果:
程序运行之前
程序运行之后:
下载源码