C++读写.ini 文件

// 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");
}

posted @ 2022-04-12 10:10  码农阿亮  阅读(460)  评论(0编辑  收藏  举报