計算機二級考試C語言輔導:剖析VC中的文件操作6

字號:

在我們寫的程序當中,總有一些配置信息需要保存下來,以便完成程序的功能,最簡單的辦法就是將這些信息寫入INI文件中,程序初始化時再讀入
    具體應用如下:
    一.將信息寫入.INI文件中.
    1.所用的WINAPI函數(shù)原型為:
    BOOL WritePrivateProfileString(
    LPCTSTR lpAppName,
    LPCTSTR lpKeyName,
    LPCTSTR lpString,
    LPCTSTR lpFileName
    );
    其中各參數(shù)的意義:
    LPCTSTR lpAppName 是INI文件中的一個字段名.
    LPCTSTR lpKeyName 是lpAppName下的一個鍵名,通俗講就是變量名.
    LPCTSTR lpString 是鍵值,也就是變量的值,不過必須為LPCTSTR型或CString型的.
    LPCTSTR lpFileName 是完整的INI文件名.
    2.具體使用方法:設現(xiàn)有一名學生,需把他的姓名和年齡寫入 c:\stud\student.ini 文件中.
    CString strName,strTemp;
    int nAge;
    strName="張三";
    nAge=12;
    ::WritePrivateProfileString("StudentInfo","Name",strName,"c:\\stud\\student.ini");
    此時c:\stud\student.ini文件中的內容如下:
    [StudentInfo]  
    3.要將學生的年齡保存下來,只需將整型的值變?yōu)樽址图纯?
    strTemp.Format("%d",nAge);
    ::WritePrivateProfileString("StudentInfo","Age",strTemp,"c:\\stud\\student.ini");
    二.將信息從INI文件中讀入程序中的變量.
    1.所用的WINAPI函數(shù)原型為:
    DWORD GetPrivateProfileString(
    LPCTSTR lpAppName,
    LPCTSTR lpKeyName,
    LPCTSTR lpDefault,
    LPTSTR lpReturnedString,
    DWORD nSize,
    LPCTSTR lpFileName
    );
    其中各參數(shù)的意義:
    前二個參數(shù)與 WritePrivateProfileString中的意義一樣.
    lpDefault : 如果INI文件中沒有前兩個參數(shù)指定的字段名或鍵名,則將此值賦給變量.
    lpReturnedString : 接收INI文件中的值的CString對象,即目的緩存器.
    nSize : 目的緩存器的大小.
    lpFileName : 是完整的INI文件名.
    2.具體使用方法:現(xiàn)要將上一步中寫入的學生的信息讀入程序中.
    CString strStudName;
    int nStudAge;
    GetPrivateProfileString("StudentInfo","Name","默認姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c:\\stud\\student.ini");
    執(zhí)行后 strStudName 的值為:"張三",若前兩個參數(shù)有誤,其值為:"默認姓名".
    3.讀入整型值要用另一個WINAPI函數(shù):
    UINT GetPrivateProfileInt(
    LPCTSTR lpAppName,
    LPCTSTR lpKeyName,
    INT nDefault,
    LPCTSTR lpFileName
    );
    這里的參數(shù)意義與上相同.使用方法如下:
    nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c:\\stud\\student.ini");