MFC讀取配置檔案

2021-06-21 21:08:53 字數 2477 閱讀 1349

在我們寫的程式當中,總有一些配置資訊需要儲存下來,以便完成程式的功能,最簡單的辦法就是將這些資訊寫入ini檔案中,程式初始化時再讀入.具體應用如下:

一.將資訊寫入.ini檔案中.

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

bool writeprivateprofilestring(

lpctstr lpkeyname,

lpctstr lpstring,

lpctstr lpfilename

); 其中各引數的意義:

lpctstr lpstring 是鍵值,也就是變數的值,不過必須為lpctstr型或cstring型的.

lpctstr lpfilename 是完整的ini檔名.

2.具體使用方法:設現有一名學生,需把他的姓名和年齡寫入 c:/stud/student.ini 檔案中. 

cstring strname,strtemp;

int nage;

strname="張三";

nage=12;

::writeprivateprofilestring("studentinfo","name",strname,"c://stud"); 

此時c:/stud/student.ini檔案中的內容如下:

[studentinfo]

name=張三

3.要將學生的年齡儲存下來,只需將整型的值變為字元型即可:

strtemp.format("%d",nage);

::writeprivateprofilestring("studentinfo","age",strtemp,"c://stud"); 

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

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

dword getprivateprofilestring(

lpctstr lpkeyname, 

lpctstr lpdefault, 

lptstr lpreturnedstring, 

dword nsize, 

lpctstr lpfilename 

); 其中各引數的意義: 

前二個引數與 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"); 

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

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

uint getprivateprofileint(

lpctstr lpkeyname, 

int ndefault, 

lpctstr lpfilename 

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

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

三.迴圈寫入多個值,設現有一程式,要將最近使用的幾個檔名儲存下來,具體程式如下:

1.寫入:

cstring strtemp,strtempa;

int i;

int ncount=6;

檔案://共有6個檔名需要儲存

for(i=0;i

strtemp.format("%d",ncount);

::writeprivateprofilestring("filecount","count",strtemp,"c://usefile");

檔案://將檔案總數寫入,以便讀出. 

2.讀出:

ncount=::getprivateprofileint("filecount","count",0,"c://usefile");

for(i=0;i  

補充四點:

1.ini檔案的路徑必須完整,檔名前面的各級目錄必須存在,否則寫入不成功,該函式返回 false 值.

2.檔名的路徑中必須為 // ,因為在vc++中, // 才表示乙個 / .

3.也可將ini檔案放在程式所在目錄,此時 lpfilename 引數為: ".".

4.從網頁中貼上源**時,最好先貼上至記事本中,再往vc中貼上,否則易造成編譯錯誤,開始時我也十分不解,好好的**怎麼就不對呢?後來才找到這個方法.還有一些**中使用了全形字符如:<,\等,也會造成編譯錯誤.

MFC 讀取配置檔案ini

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

MFC 讀取配置檔案(封裝)

目前只封裝了string型別的讀和寫配置檔案 利用了 windows api 現有的函式,很簡單 writeprivateprofilestringw in opt lpcwstr lpkeyname,in opt lpcwstr lpstring,in opt lpcwstr lpfilename...

讀取配置檔案

類載入器 1 直接用class.forname 類的路徑名 class.forname com.hsf.classloader.classloader 2 用classloder 類載入器 inputstream in classloader.getsystemresourceasstream aa...