// RWIniTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<atlstr.h>
#include<stdlib.h>

using namespace std;

void  ReadIniTest() {


	/* test.ini "="号两边可以加空格,也可以不加
  [Font]
  name=宋体
  size= 12pt
  color = RGB(255,0,0)
  [Layout]
  [Body]
  */

	CString strCfgPath = "D:\\test.ini"; //注意:'\\'
	LPCTSTR lpszSection = _T("Font");
	int n = GetPrivateProfileInt(_T("FONT"), _T("size"), 9, strCfgPath);//n=12
	CString str;
	GetPrivateProfileString(lpszSection, _T("size"), _T("9pt"), str.GetBuffer(MAX_PATH), MAX_PATH, strCfgPath);
	str.ReleaseBuffer();//str="12pt"

	TCHAR buf[200] = { 0 };
	int nSize = sizeof(buf) / sizeof(buf[0]);
	GetPrivateProfileString(lpszSection, NULL, _T(""), buf, nSize, strCfgPath);
	//buf: "name\0size\0color\0\0"

	memset(buf, 0, sizeof(buf));
	GetPrivateProfileString(NULL, _T("size"), _T(""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL
	//可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);
	//buf: "Font\0Layout\0Body\0\0"

	memset(buf, 0, sizeof(buf));
	GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);
	//buf: "name=宋体\0size=12pt\0color=RGB(255,0,0)\0\0"  此时“=”两边不会有空格

	memset(buf, 0, sizeof(buf));
	GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);
	//buf: "Font\0Layout\0Body\0\0"

}

void WriteIniTest() {

	CString strCfgPath = "D:\\test.ini"; //注意:'\\'

	WritePrivateProfileString(_T("Layout"), _T("left"), _T("100"), strCfgPath);
	WritePrivateProfileString(_T("Layout"), _T("top"), _T("80"), strCfgPath);
	//删除某Section,包括[Layout]和其下所有Keys=Value
	WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);
	//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]
	WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);
	//而:WritePrivateProfileSection(NULL, NULL, strCfgPath);什么也不做,因Section为NULL
}


int main()
{
	ReadIniTest();
	WriteIniTest();

	system("pause");
}

技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!

开源库地址,欢迎点亮:

GitHub: https://github.com/ITMingliang

Gitee:  https://gitee.com/mingliang_it

GitLab:  https://gitlab.com/ITMingliang

建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群

C++读写.ini 文件_#include