C++對ini配置檔案與xml配置檔案的讀寫
阿新 • • 發佈:2019-02-04
1、ini檔案的讀寫
在遊戲與軟體開發過程中,我們經常會使用ini的配置檔案,為遊戲或軟體配置相關的引數,因此就有必要對ini檔案進行讀寫操作。
下面介紹C++在讀寫ini檔案中,常用到的幾個函式:
1) 讀.ini檔案:DWORD GetPrivateProfileString( LPCTSTR lpAppName, // INI檔案中的一個欄位名[節名]可以有很多個節名 LPCTSTR lpKeyName, // lpAppName 下的一個鍵名,也就是裡面具體的變數名 LPCTSTR lpDefault, // 如果lpReturnedString為空,則把個變數賦給lpReturnedString LPTSTR lpReturnedString, // 存放鍵值的指標變數,用於接收INI檔案中鍵值(資料)的接收緩衝區 DWORD nSize, // lpReturnedString的緩衝區大小 LPCTSTR lpFileName // INI檔案的路徑 );
UINT GetPrivateProfileInt( LPCTSTR lpAppName, // INI檔案中的一個欄位名[節名]可以有很多個節名 LPCTSTR lpKeyName, // lpAppName 下的一個鍵名,也就是裡面具體的變數名 INT nDefault, // 如果沒有找到指定的資料返回,則把個變數值賦給返回值 LPCTSTR lpFileName // INI檔案的路徑 );
2)寫.ini檔案
MAX_PATH:是微軟最大路徑佔的位元組所設的巨集 讀取ini檔案函式BOOL WritePrivateProfileString( LPCTSTR lpAppName, // INI檔案中的一個欄位名[節名]可以有很多個節名 LPCTSTR lpKeyName, // lpAppName 下的一個鍵名,也就是裡面具體的變數名 LPCTSTR lpString, // 鍵值,也就是資料 LPCTSTR lpFileName // INI檔案的路徑 );
void ReadIniInfo(const char* szRoomName) { //構梏ini檔案路徑 CString strFileName,str; str.Format(TEXT("%s.ini"),szRoomName); char szPath[MAX_PATH]; GetCurrentDirectory(MAX_PATH, szPath); strFileName.Format(TEXT("%s\\%s"), szPath, str); //讀取ini檔案資訊 int m_nRoomNum = GetPrivateProfileInt(TEXT("Config"), TEXT("RoomNum"), 0, strFileName); }
ini檔案配置示例: [Config] RoomNum=100
2、xml檔案的讀寫
xml檔案與ini檔案一樣,在遊戲與軟體開發的過程中,能進行配置相關的屬性,只需要對xml進行修改就可以進行遊戲與軟體的相關配置,因此在開發過程中也很有必要對xml檔案進行讀寫操作。
在C++中,對xml檔案進行讀寫可以使用一個工具類rapidXml,這個工具類具體檔案如圖所示:
具體的原始碼可以到這裡進行下載:點選開啟連結
使用rapidXml對xml檔案進行讀寫的方法可以參考:點選開啟連結
除了使用rapidXml進行xml檔案的讀寫外,還可以使用另外一個工具類進行讀寫xml檔案,那就是tinyxml工具類,這個工具只有兩個檔案tinystr.h和tinyxml.h。
具體原始碼可以到這裡進行下載:點選開啟連結
下面將介紹如何使用tinyxml進行xml檔案的讀寫:
假設xml配置檔案的內容為:
<?xml version="1.0" encoding="gb2312"?>
<Root>
<Config RoomId="10"
RoomName="遊戲房間“>
</Config>
</Root>
1)讀xml檔案
void readXml()
{
TiXmlDocument TiDoc;
TiDoc.LoadFile("config.xml");
TiXmlElement * pRoot = TiDoc.RootElement();
for(TiXmlElement * pElem = pRoot->FirstChildElement("Config");pElem != NULL; pElem = pElem->NextSiblingElement("Config"))
{
int roomId = atoi(pElem->Attribute("RoomId"));
std::string roomName = pElem->Attribute("RoomName");
}
}
2)寫xml檔案
void writeXml()
{
TiXmlDocument TiDoc("config.xml");
TiXmlDeclaration declaration("1.0", "gb2312", "yes");
doc.InsertEndChild(declaration);
TiXmlElement pRootElem("Root");
TiXmlElement pElem("Config");
pElem.SetAttribute("RoomId", 10);
pElem.SetAttribute("RoomName", "遊戲房間");
pRootElem.InsertEndChild(pElem);
TiDoc.InsertEndChild(pRootElem);
TiXmlElement * pRoot = TiDoc.RootElement();
}