建立一个win32控制台项目,输入一下程序,实现从配置文件test.ini中读取参数的值。
1.::GetPrivateProfileInt:读取int型参数的值;
2.GetPrivateProfileString:读取string型参数的值;
3.GetPrivateProfileSectionNames:读取所有节点名。
// testINI.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include<string>
#include <atlstr.h>
using std::string;
int _tmain(int argc, _TCHAR* argv[])
{ //从配置文件中读int型变量 below
string strCurPath;
TCHAR *path = new TCHAR[MAX_PATH];
ZeroMemory(path, MAX_PATH); //path:指向一块准备用0来填充的内存区域的开始地址
GetCurrentDirectory(MAX_PATH, path);//返回操作系统的当前目录
GetModuleFileName(NULL,path,MAX_PATH);//获取当前应用程序主目录(.exe)
strCurPath = path;
strCurPath = strCurPath.substr(0,strCurPath.rfind('\\')+1).append("test.ini"); //项目根目录下有配置文件test.ini
int nValue = ::GetPrivateProfileInt("ItemName","a",0,strCurPath.c_str()); //从配置文件中读int型变量,项名ItemName,变量名a,默认值0. 结果:nValue = 1000
//从配置文件中读int型变量 above
//从配置文件中读string型变量 below
TCHAR szFilePath[MAX_PATH + 1] = {0};
GetModuleFileName(NULL, szFilePath, MAX_PATH);//获取当前应用程序主目录(.exe)
(_tcsrchr(szFilePath, _T('\\')))[1] = 0;//_tcsrchr:第一个出现字符‘\’的地方设置为0,即就是将exe去掉
CString strFile = szFilePath;
CString strFilePath = strFile + "test.ini";
TCHAR chBuffer[256] = {0};
GetPrivateProfileString("ItemName2", "Name", _T(""), chBuffer, sizeof(chBuffer), strFilePath);//从配置文件中读string型变量,默认值为""
CString strName = "";
strName.Format("%s", chBuffer); //strName = AAAAA
memset(chBuffer , 0x00 , 256);
//从配置文件中读string型变量 above
//从配置文件中读所有节名 below
TCHAR chSectionNames[2048] = {0}; //所有节名组成的字符数组
::GetPrivateProfileSectionNames(chSectionNames,2048,strFilePath);//得到的section名称存在第一个参数指定的内存中,每个名称之间用一个0字符隔开,最后一个名字用两个0字符作为结尾。
//结果chSectionNames = ItemName0ItemName200
//从配置文件中读所有节名 above
return 0;
}
配置文件内容见下图