C++ ini

具體應用如下:

  一.將信息寫入.INI文件中.

  1.所用的WINAPI函數原型爲:

C/C++ code
BOOL WritePrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpString,
LPCTSTR lpFileName
);



  其中各參數的意義:

   LPCTSTR lpAppName 是INI文件中的一個字段名.

   LPCTSTR lpKeyName 是lpAppName下的一個鍵名,通俗講就是變量名.

   LPCTSTR lpString 是鍵值,也就是變量的值,不過必須爲LPCTSTR型或CString型的.

   LPCTSTR lpFileName 是完整的INI文件名.

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

C/C++ code
CString strName,strTemp;
int nAge;
strName="張三";
nAge=12;
::WritePrivateProfileString("StudentInfo","Name",strName,"c://stud//student.ini");


  此時c:/stud/student.ini文件中的內容如下:

   [StudentInfo]
   

  3.要將學生的年齡保存下來,只需將整型的值變爲字符型即可:

C/C++ code
strTemp.Format("%d",nAge);
::WritePrivateProfileString("StudentInfo","Age",strTemp,"c://stud//student.ini");


二.將信息從INI文件中讀入程序中的變量.

  1.所用的WINAPI函數原型爲:

C/C++ code
DWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault,
LPTSTR lpReturnedString,
DWORD nSize,
LPCTSTR lpFileName
);



  其中各參數的意義:

   前二個參數與 WritePrivateProfileString中的意義一樣.

   lpDefault : 如果INI文件中沒有前兩個參數指定的字段名或鍵名,則將此值賦給變量.

   lpReturnedString : 接收INI文件中的值的CString對象,即目的緩存器.

   nSize : 目的緩存器的大小.

   lpFileName : 是完整的INI文件名.

  2.具體使用方法:現要將上一步中寫入的學生的信息讀入程序中.

C/C++ code
CString strStudName;
int nStudAge;
GetPrivateProfileString("StudentInfo","Name","默認姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c://stud//student.ini");


  執行後 strStudName 的值爲:"張三",若前兩個參數有誤,其值爲:"默認姓名".

  3.讀入整型值要用另一個WINAPI函數:

C/C++ code
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
INT nDefault,
LPCTSTR lpFileName
);



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

C/C++ code
nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c://stud//student.ini");



三.循環寫入多個值,設現有一程序,要將最近使用的幾個文件名保存下來,具體程序如下:

  1.寫入:

C/C++ code
CString strTemp,strTempA;
int i;
int nCount=6;
file://共有6個文件名需要保存
for(i=0;i {strTemp.Format("%d",i);
strTempA=文件名;
file://文件名可以從數組,列表框等處取得.
::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA,
"c://usefile//usefile.ini");
}
strTemp.Format("%d",nCount);
::WritePrivateProfileString("FileCount","Count",strTemp,"c://usefile//usefile.ini");


file://將文件總數寫入,以便讀出.

  2.讀出:
C/C++ code

nCount=::GetPrivateProfileInt("FileCount","Count",0,"c://usefile//usefile.ini");
for(i=0;i {strTemp.Format("%d",i);
strTemp="FileName"+strTemp;
::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c://usefile//usefile.ini");



file://使用strTempA中的內容.

}

  補充四點:

   1.INI文件的路徑必須完整,文件名前面的各級目錄必須存在,否則寫入不成功,該函數返回 FALSE 值.

   2.文件名的路徑中必須爲 // ,因爲在VC++中, // 才表示一個 / .

   3.也可將INI文件放在程序所在目錄,此時 lpFileName 參數爲: ".//student.ini".

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章