VS 儲存INI配置檔案和讀取配置檔案

2021-06-06 08:33:32 字數 2572 閱讀 1223

ini檔案簡介

在我們寫程式時,總有一些配置資訊需要儲存下來,以便在下一次啟動程式完成初始化,這實際上是一種類持久化。將一些資訊寫入ini檔案(initialization file)中,可完成簡單的持久化支援。

windows提供了api介面用於操作ini檔案,其支援的ini檔案格式一般如下:

[section1]

key11=value11

key12=value12

[section2]

key21=value21

key22=value22

[sectionn]

keyn1=valuen1

keyn2=valuen2

一般乙個ini檔案可有n個節,每節可有n個鍵名及值對應,每個鍵名及其值以等式形式佔一行。

一般鍵的名稱可任取,不過建議用有意義的字元及詞構成。值一般可為整數和字串,其它型別要進行轉換。

常見的系統配置檔案:

c:/boot.ini

c:/windows/win.ini

c:/windows/system.ini

c:/windows/desktop.ini

c:/windows/resources/themes/windows classic.theme

注意,字串存貯在ini檔案中時沒有引號;key和value之間的等號前後不容空格;注釋以分號「;」開頭。

vc中操作ini檔案的api

(1)作業系統配置檔案win.ini的函式:

函式名功能

getprofilesection

key1=value1/0key2=value2/0…keyn=valuen/0/0

getprofilestring

getprofileint

writeprofilesection

lpstring字串形式同getprofilesection中的lpreturnedstring。

writeprofilestring

(2)操作使用者自定義配置檔案(privateprofile.ini)的函式:

函式名功能

getprivateprofilesectionnames

讀取lpfilename指定的配置檔案中所有的節名。lpszreturnbuffer字串形式如下:

section1/0section2/0…sectionn/0/0

getprivateprofilesection

同getprofilesection。

getprivateprofilestring

同getprofilestring。

getprivateprofileint     

同getprofileint

getprivateprofilestruct

須同writeprivateprofilestruct配套使用。

writeprivateprofilesection

同writeprofilesection

writeprivateprofilestring

同writeprofilestring

writeprivateprofilestruct

不常用。

注意:(1)使用得最頻繁的是getprivateprofilestring 和writeprivateprofilestring,沒有writeprofileint/writeprivateprofileint函式。

(2)get系列讀取節鍵值,如果檔案路徑有誤或節鍵名不對則返回設定的預設值。

(3)訪存自定義配置檔案時,檔案路徑lpfilename必須完整,檔名前面的各級目錄必須存在。如果lpfilename檔案路徑不存在,則函式返回false,getlasterror() = error_path_not_found。如果路徑正確,但是檔案不存在,則該函式將先建立該檔案。如果路徑及檔案存在,則在現有ini檔案基礎上進行讀寫。

如果lpfilename 只指定檔名而沒有路徑的話,呼叫api將會去windows 的安裝目錄去查詢而不會在當前目錄查詢。

(4)要對呼叫api的模組(exe)所在目錄下進行配置檔案操作,可使用形如「.的相對路徑,注意轉義符。

(5)呼叫writeprivateprofilesection,若引數三lpstring為null,則可將對應section的全部內容清空;呼叫writeprivateprofilestring,若引數三lpstring為null,則可將對應key刪除。

跨平台配置檔案

ini檔案本質是對檔案和字串的處理,因此在跨平台專案中的配置檔案可以基於中的標c檔案file,然後實現像類似以上對節([section])、鍵(key)和值(value)的字串讀寫功能。

在c/c++程式中要使用xml做為配置檔案,涉及到xml的解析。windows平台可使用msxml對xml進行解析,參考《msxml建立和解析xml示例》,跨平台可以考慮自己實現,或使用c++ boost正規表示式,或選擇free c or c++ xml parser libraries,如xmlparser、tinyxml、cmarkup、libxml等。

cinifile類

以下提供對windows操作ini檔案的api的簡單封裝類cinifile。

C 讀取ini配置檔案

using system using system.io using system.runtime.interopservices using system.text todo 在此處新增建構函式邏輯 public class iniclass 寫入ini檔案 專案名稱 如 typename 鍵 值...

MFC 讀取配置檔案ini

一.將資訊寫入.ini檔案中.1.所用的winapi函式原型為 bool writeprivateprofilestring lpctstr lpkeyname,lpctstr lpstring,lpctstr lpfilename 其中引數 lpctstr lpstring 是鍵值,也就是變數的值...

C 讀取ini配置檔案

雖然微軟早已經建議在windows中用登錄檔代替ini檔案,但是在實際應用中,ini檔案仍然有用武之地,尤其現在綠色軟體的流行,越來越多的程式將自己的一些配置資訊儲存到了ini檔案中。section key valuevc中提供了api函式進行ini檔案的讀寫操作,但是微軟推出的c 程式語言中卻沒有...