讀寫配置檔案

2021-04-12 20:51:32 字數 2504 閱讀 1779

windows作業系統專門為此提供了6個api函式來對配置設定檔案進行讀、寫:

getprivateprofileint() 從私有初始化檔案獲取整型數值

getprivateprofilestring() 從私有初始化檔案獲取字串型值

getprofileint 從win.ini 獲取整數值

getprofilestring 從win.ini 獲取字串值

writeprivateprofilestring 寫字串到私有初始化檔案

writeprofilestring 寫字串到win.ini

我們可以把檢視類的:oninitialupdate() 函式作為程式啟動時讀取配置檔案的入口,配置檔案的儲存格式如下:

[section 1]

xpos=300

ypos=200

[section 2]

text=hello

僅有兩個節,xpos和ypos標明了待顯示資訊的座標,而待顯示的資訊儲存在第二節的text項中,用讀取訪問私有配置設定檔案的api函式將其分別讀入到變數m_nxpos,m_nypos和m_strtext中,並通過invalidate()呼叫ondraw()函式,在其內用textout函式將該資訊在讀取的座標位置顯示出來:

m_nxpos=getprivateprofileint("section 1", //節名

"xpos", //項名

0, //沒找到此項時的預設返回值

"c://test//debug//test.ini"); //配置檔案的準確路徑

m_nypos=getprivateprofileint("section 1","ypos",0,exefullpath);

char buf[256];

len=getprivateprofilestring("section 2", //節名

"text", //項名

"no text", //沒找到此項時的返回值

buf, //目標緩衝區位址

256, //目標緩衝區長度

"c://test//debug//test.ini"); //配置檔案的準確路徑

for(int i=0;itchar exefullpath[max_path]; // max_path在api中有定義,為128

int len=getmodulefilename(null,

exefullpath, //應用程式的全路徑存放位址

max_path);

cstring path="//test.ini"; //配置檔名

::strcpy(exefullpath+len-13,path); //組合出配置檔案的全路徑

寫配置檔案也基本類似,只是需要把數值型別的變數格式化成字串再行儲存:

str.format("%d",m_nxpos);

writeprivateprofilestring("section 1","xpos",str,exefullpath);

str.format("%d",m_nypos);

writeprivateprofilestring("section 1","ypos",str,exefullpath);

writeprivateprofilestring("section 2","text",m_strtext,exefullpath);

我們一定遇到過這樣的程式:在執行過一遍以後,重啟系統會自動載入該程式,其實除了在啟動選單和登錄檔新增資訊外,也可以用writeprofilestring()函式向win.ini的"windows"節的"run"專案新增應用程式的全路徑來實現,這要比其它兩種方法簡便的多,而且也比較安全。

二.將資訊從ini檔案中讀入程式中的變數.

1.所用的winapi函式原型為:

其中各引數的意義:

前二個引數與 writeprivateprofilestring中的意義一樣.

lpdefault : 如果ini檔案中沒有前兩個引數指定的欄位名或鍵名,則將此值賦給變數.

lpreturnedstring : 接收ini檔案中的值的cstring物件,即目的快取器.

nsize : 目的快取器的大小.

lpfilename : 是完整的ini檔名.

2.具體使用方法:現要將上一步中寫入的學生的資訊讀入程式中.

cstring strstudname;

int nstudage;

getprivateprofilestring("studentinfo","name","預設姓名",strstudname.getbuffer(max_path),max_path,"c://stud//student.ini");

執行後 strstudname 的值為:"張三",若前兩個引數有誤,其值為:"預設姓名".

3.讀入整型值要用另乙個winapi函式:

這裡的引數意義與上相同.使用方法如下:

nstudage=getprivateprofileint("studentinfo","age",10,"c://stud//student.ini");

讀寫配置檔案

procedure curstepchanged curstep tsetupstep varsetupname string inipath string begin case curstep of ssinstall 複製檔案前 begin end sspostinstall 完成複製 begi...

讀寫配置檔案

寫配置檔案 include include include include using std cout using std endl int main int nlen strlen d myinifile.ini 16 nlen strlen lppath 0 strcpy s lppath,s...

讀寫配置檔案

配置檔案讀寫系統方法和測試函式 include readconfig.h define cfgname test.txt void mymenu inttgetcfg char value 1024 int vlen 0 printf nplease input key scanf s,name r...