//对ini文件的处理一例!
对.ini文件的操作
例如我的Config.ini文件如下:
[Config]
TCP Host=255.0.0.1
TCP Port=8888
UDP Port=8200
其读写操作可以如下:
int k;
char linebuf[30];
char workdir[64],sFileN[100];
getcwd(workdir,50); //获得当前运行文件路径 //用getcwd需#include "direct.h"
wsprintf(sFileN,"%s//config.ini",(LPSTR)workdir); //若用GetCurrentDirectory()则不需
int m_tcpport=GetPrivateProfileInt("Config", "TCP Port", 0, sFileN);
int m_udpport=GetPrivateProfileInt("Config", "UDP Port", 0, sFileN);
GetPrivateProfileString ("Config", "TCP Host", NULL, linebuf, 99, sFileN);
//读出了数据到linebuf
//以下是往.ini文件中写入数据
WritePrivateProfileString("Config","TCP Port","8888",sFileN);
WritePrivateProfileString("Config","TCP Host","255.0.0.1 ",sFileN);
附录:
BOOL WritePrivateProfileString(
LPCTSTR lpAppName, // section name
LPCTSTR lpKeyName, // key name
LPCTSTR lpString, // string to add
LPCTSTR lpFileName // initialization file
);
给你一个“性感”类:
http://www.youkuaiyun.com/expert/topic/783/783785.xml?temp=.9687311
#ifndef INIFILE_H
#define INIFILE_H
class CIniFile
{
public:
CIniFile();
virtual ~CIniFile();
// Operations
public:
BOOL SetProfileInt(CString pParent, CString pPrivateName, int pValue);
BOOL SetProfileString(CString pParent, CString pPrivateName, CString pValue);
int GetProfileInt(CString pParent, CString pPrivateName);
CString GetProfileString(CString pParent, CString pPrivateName);
protected:
private:
CString fileName;
};
#endif
//cpp
#include "stdafx.h"
#include "IniFile.h"
CIniFile::CIniFile()
{
fileName = _T("");
TCHAR exeFullPath[MAX_PATH];
GetModuleFileName(NULL, exeFullPath, MAX_PATH);
CString tmp;
tmp.Format("%s", exeFullPath);
int ret = tmp.Find("//", 0);
while (ret != -1)
{
fileName += tmp.Left(ret + 1);
CString pp;
pp = tmp.Right(strlen(tmp) - ret - 1);
tmp = pp;
ret = tmp.Find("//", 0);
}
fileName += "main.ini"; //配置文件名
CFile file;
if (!file.Open(fileName, CFile::modeRead, NULL))
{
file.Open(fileName, CFile::modeCreate | CFile::modeWrite, NULL);
char pBuf[] = "";
file.Write(pBuf, sizeof(pBuf));
}
file.Close();
}
CIniFile::~CIniFile()
{
}
CString CIniFile::GetProfileString(CString pParent, CString pPrivateName)
{
CString tmp;
GetPrivateProfileString(pParent, pPrivateName, "", tmp.GetBuffer(MAX_PATH), MAX_PATH, fileName);
tmp.ReleaseBuffer();
return tmp;
}
int CIniFile::GetProfileInt(CString pParent, CString pPrivateName)
{
int pValue;
pValue = GetPrivateProfileInt(pParent, pPrivateName, 0, fileName);
return pValue;
}
BOOL CIniFile::SetProfileString(CString pParent, CString pPrivateName, CString pValue)
{
return WritePrivateProfileString(pParent, pPrivateName, pValue, fileName);
}
BOOL CIniFile::SetProfileInt(CString pParent, CString pPrivateName, int pValue)
{
CString tmp;
tmp.Format("%d", pValue);
return WritePrivateProfileString(pParent, pPrivateName, tmp, fileName);
}