1. 程式人生 > 其它 >C++讀寫.ini 檔案

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