从配置文件(.ini)中获取变量的值

建立一个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;
}

配置文件内容见下图

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值